Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the default argument values in Python

Tags:

python

How can I programmatically access the default argument values of a method in Python? For example, in the following

def test(arg1='Foo'):
    pass

how can I access the string 'Foo' inside test?

like image 229
Randomblue Avatar asked Jan 10 '12 16:01

Randomblue


People also ask

How do you call a default argument 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.

What is default argument function in Python?

Default argument is fallback value In Python, a default parameter is defined with a fallback value as a default argument. Such parameters are optional during a function call. If no argument is provided, the default value is used, and if an argument is provided, it will overwrite the default value.

Where the values of default arguments should be provided?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument.

How do you find arguments in Python?

To access command-line arguments from within a Python program, first import the sys package. You can then refer to the full set of command-line arguments, including the function name itself, by referring to a list named argv. In either case, argv refers to a list of command-line arguments, all stored as strings.


2 Answers

They are stored in test.func_defaults (python 2) and in test.__defaults__ (python 3).

As @Friedrich reminds me, Python 3 has "keyword only" arguments, and for those the defaults are stored in function.__kwdefaults__

like image 164
Ricardo Cárdenes Avatar answered Nov 12 '22 07:11

Ricardo Cárdenes


Consider:

def test(arg1='Foo'):
    pass

In [48]: test.func_defaults
Out[48]: ('Foo',)

.func_defaults gives you the default values, as a sequence, in order that the arguments appear in your code.

Apparently, func_defaults may have been removed in python 3.

like image 39
Marcin Avatar answered Nov 12 '22 07:11

Marcin