Accessing default argument values ​​in Python

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

def test(arg1='Foo'):
    pass

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

+5
source share
4 answers

They are stored in test.func_defaults

+14
source

Consider:

def test(arg1='Foo'):
    pass

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

.func_defaults gives default values ​​as a sequence so that the arguments appear in your code.

Apparently func_defaultscan be removed in python 3.

+4
source

. test test . inspect , : Python ?

, test :

def test(arg1='foo'):
    print test.__defaults__[0]

Will output foo. But the link to testwill only work until it is testactually defined:

>>> test()
foo
>>> other = test
>>> other()
foo
>>> del test
>>> other()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in test
NameError: global name 'test' is not defined

So, if you are going to transfer this function, you really need to go to the route inspect: (

+2
source

It is not very elegant (in general), but it does what you want:

def test(arg1='Foo'):
    print(test.__defaults__)

test(arg1='Bar')

Also works with Python 3.x.

0
source

All Articles