Simple recipe for finding out a function argument's default value.
Can be used as a poor-man's function attribute, see the examples.
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>
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".