Skip to content

Commit

Permalink
Merge pull request #4615 from niboshi/bp-4551-argument-exception-message
Browse files Browse the repository at this point in the history
[backport] Improve chainer.utils.argument exception message
  • Loading branch information
okuta committed Apr 15, 2018
2 parents a562958 + b200988 commit 5643cae
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
10 changes: 8 additions & 2 deletions chainer/utils/argument.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import inspect


def check_unexpected_kwargs(kwargs, **unexpected):
for key, message in unexpected.items():
if key in kwargs:
Expand All @@ -8,8 +11,11 @@ def parse_kwargs(kwargs, *name_and_values):
values = [kwargs.pop(name, default_value)
for name, default_value in name_and_values]
if kwargs:
args = ', '.join(["'%s'" % arg for arg in kwargs.keys()])
raise TypeError('got unexpected keyword argument(s) %s' % args)
caller = inspect.stack()[1]
args = ', '.join(repr(arg) for arg in sorted(kwargs.keys()))
message = caller[3] + \
'() got unexpected keyword argument(s) {}'.format(args)
raise TypeError(message)
return tuple(values)


Expand Down
24 changes: 24 additions & 0 deletions tests/chainer_tests/utils_tests/test_argument.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import unittest

import six

from chainer import testing
from chainer.utils.argument import parse_kwargs


class TestArgument(unittest.TestCase):

def test_parse_kwargs(self):

def test(**kwargs):
return parse_kwargs(kwargs, ('foo', 1), ('bar', 2))

self.assertEqual(test(), (1, 2))
self.assertEqual(test(bar=1, foo=2), (2, 1))

msg = "test\(\) got unexpected keyword argument\(s\) 'ham', 'spam'"
with six.assertRaisesRegex(self, TypeError, msg):
test(spam=1, ham=2)


testing.run_module(__name__, __file__)

0 comments on commit 5643cae

Please sign in to comment.