Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the default value for a keyword argument in Python?

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?

like image 305
planetp Avatar asked Oct 16 '14 09:10

planetp


People also ask

How do you call a default value in Python?

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.

How do you get keyword arguments in Python?

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.

How do you unpack a keyword argument in Python?

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.

Can you set default values to Python arguments?

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.


1 Answers

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}
like image 148
Martijn Pieters Avatar answered Oct 07 '22 06:10

Martijn Pieters