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__
Solution 1:
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.
Solution 2:
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}
Post a Comment for "What Is The Use Of __kwdefaults__ Which Is A Function Object Attribute?"