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__
?
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With