开发者

Uses of combining **kwargs and key word arguments in a method signature

开发者 https://www.devze.com 2023-01-29 18:26 出处:网络
Is there a use for combining **kwargs and keyword arguments in a method signature? >>> def f(arg, kw=[123], *args, **kwargs):

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 prints.)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消