I'm trying to use the __defaults__
attribute of a function object to get default values for arguments. It works for this case:
>>> def test(x, y=1): pass
...
>>> test.__defaults__
(1,)
but for this it doesn't:
>>> def test(*args, y=1): pass
...
>>> test.__defaults__
>>>
Why does test.__defaults__
contain None
? How can I get the default value for the parameter in this case?
Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.
Embrace keyword arguments in Python Consider using the * operator to require those arguments be specified as keyword arguments. And remember that you can accept arbitrary keyword arguments to the functions you define and pass arbitrary keyword arguments to the functions you call by using the ** operator.
A double asterisk ** is used for unpacking a dictionary and passing it as keyword arguments during the function call. Example 1: Unpacking dictionary during the function call. mul(**d )→ It will unpack the elements in the dictionary and pass it as keyword arguments during the function call.
In addition to passing arguments to functions via a function call, you can also set default argument values in Python functions. These default values are assigned to function arguments if you do not explicitly pass a parameter value to the given argument. Parameters are the values actually passed to function arguments.
You created a function with a keyword-only argument; you cannot use y
as a positional argument. Keyword-argument defaults are stored in __kwdefaults__
:
>>> test.__kwdefaults__
{'y': 1}
Quoting the Callable Types section of the Standard Types hierarchy datamodel documentation:
__kwdefaults__
: A dict containing defaults for keyword-only parameters.
You should really use the inspect
module Signature
object to introspect callables however; it'll take care of details like these by providing you with a rich object instead:
>>> sig = inspect.signature(test)
>>> {name: param.default for name, param in sig.parameters.items()
... if not param.default is param.empty}
{'y': 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