Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of __kwdefaults__ which is a function object attribute?

Function object has attributes __defaults__ and __kwdefaults__. I see that if a function has some default arguments then they are put as a tuple to __defaults__ but __kwdefaults__ is None. When is used attribute __kwdefaults__?

like image 217
scdmb Avatar asked Jul 08 '13 18:07

scdmb


2 Answers

def foo(arg1, arg2, arg3, *args, kwarg1="FOO", kwarg2="BAR", kwarg3="BAZ"):
    pass

print(foo.__kwdefaults__)

Output (Python 3):

{'kwarg1': 'FOO', 'kwarg2': 'BAR', 'kwarg3': 'BAZ'}

Since the *args would swallow all non-keyword arguments, the arguments after it have to be passed with keywords. See PEP 3102.

like image 176
Markus Unterwaditzer Avatar answered Nov 05 '22 00:11

Markus Unterwaditzer


It is used for keyword-only arguments:

>>> def a(a, *, b=2): pass
...
>>> a.__kwdefaults__
{'b': 2}

>>> def a(*args, a=1): pass
...
>>> a.__kwdefaults__
{'a': 1}
like image 32
Pavel Anossov Avatar answered Nov 05 '22 01:11

Pavel Anossov