Welcome, guest | Sign In | My Account | Store | Cart

Simple recipe for finding out a function argument's default value.

Can be used as a poor-man's function attribute, see the examples.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def get_arg_default(func, arg_name):
    import inspect
    args, varargs, varkwargs, defaults = inspect.getargspec(func)
    have_defaults = args[-len(defaults):]

    if arg_name not in args:
        raise ValueError("Function does not accept arg '%s'" % arg_name)

    if arg_name not in have_defaults:
        raise ValueError("Parameter '%s' doesn't have a default value" % arg_name)

    return defaults[list(have_defaults).index(arg_name)]

Can be used as a poor-man's function attribute, e.g. this code: <pre> def foo(x, y, author="Winnie The Pooh"): ...

print "Author is:", get_arg_default(foo, "author") </pre>

Will print:

<pre> Author is: Winnie The Pooh </pre>

1 comment

Chris Arndt 17 years, 11 months ago  # | flag

Easier when you know the position of the argument. When you know the position of the argument in the function's argument list, you can use the standard function attribute "func_defaults".

def func(foo, bar="baz", spamm="eggs"):
    pass

# index not counting non-default args
print func.func_defaults[1]

... will print "eggs"

See http://www.python.org/doc/2.4.3/ref/types.html#l2h-76
Created by Ori Peleg on Wed, 19 Apr 2006 (PSF)
Python recipes (4591)
Ori Peleg's recipes (15)

Required Modules

Other Information and Tasks