Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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):
  File "<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...

like image 743
explodes Avatar asked Nov 29 '22 19:11

explodes


2 Answers

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.

like image 167
robert Avatar answered Dec 06 '22 17:12

robert


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.

like image 32
Falmarri Avatar answered Dec 06 '22 19:12

Falmarri