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
?
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
?
Consider:
.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.This isn't very elegant (at all), but it does what you want:
Works with Python 3.x too.
They are stored in
test.func_defaults
(python 2) and intest.__defaults__
(python 3).As @Friedrich reminds me, Python 3 has "keyword only" arguments, and for those the defaults are stored in
function.__kwdefaults__
Ricardo Cárdenes is on the right track. Actually getting to the function
test
insidetest
is going to be a lot more tricky. Theinspect
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:Will print out
foo
. But refering totest
will only work, as long astest
is actually defined:So, if you intend on passing this function around, you might really have to go the
inspect
route :(