Randomblue
Randomblue

Reputation: 116263

Accessing the default argument values in 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?

Upvotes: 8

Views: 1446

Answers (4)

Ricardo Cárdenes
Ricardo Cárdenes

Reputation: 9172

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__

Upvotes: 17

Daren Thomas
Daren Thomas

Reputation: 70314

Ricardo Cárdenes is on the right track. Actually getting to the function test inside test is going to be a lot more tricky. The inspect module will get you further, but it is going to be ugly: Python code to get current function into a variable?

As it turns out, you can refer to test inside the function:

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

Will print out foo. But refering to test will only work, as long as test is actually 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 intend on passing this function around, you might really have to go the inspect route :(

Upvotes: 2

Marcin
Marcin

Reputation: 49816

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.

Upvotes: 5

Rob Wouters
Rob Wouters

Reputation: 16327

This isn't very elegant (at all), but it does what you want:

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

test(arg1='Bar')

Works with Python 3.x too.

Upvotes: 0

Related Questions