Is there a use for combining **kwargs and keyword arguments in a method signature?
>>> def f(arg, kw=[123], *args, **kwargs):
... print arg
... print kw
... print args
... print kwargs
...
>>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def')
Traceback (most recent call last):
Fi开发者_JAVA技巧le "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'kw'
It seems useless, but maybe someone has found a nice trick for it...
In Python 3 you can have keyword-only arguments (PEP 3102). With these, your function would look like this:
>>> def f(arg, *args, kw=[123], **kwargs):
... print(arg)
... print(kw)
... print(args)
... print(kwargs)
>>> f(5, 'a', 'b', 'c', kw=['abc'], kw2='def')
5
('a', 'b', 'c')
['abc']
{'kw2': 'def'}
(Note that while I changed the order of the arguments I did not change the order of the print
s.)
In Python 2 you can't have a keyword argument after a varargs argument, but in Python 3 you can, and it makes that argument keyword-only.
Also, be wary of putting mutable objects as default parameters.
You're assigning kw twice.
In this call f(5, 'a', 'b', 'c', kw=['abc'], kw2='def')
, arg=5, kw='a', *args = ('b','c'), and then you're trying to assign kw again.
精彩评论