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

The function object has the attributes __defaults__ and __kwdefaults__ . I see that if a function has some default arguments, then they are placed as a tuple in __defaults__ , and __kwdefaults__ is None . When is the __kwdefaults__ attribute __kwdefaults__ ?

+6
source share
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 *args will swallow all arguments without a keyword, the arguments after that must be passed with the keywords. See PEP 3102 .

+7
source

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} 
+6
source

Source: https://habr.com/ru/post/948971/


All Articles