How do I get a dictionary of argument names with their default values?

Fredrik Lundh fredrik at pythonware.com
Thu Dec 22 18:04:07 EST 2005


"Noah" <noah at noah.org> wrote:

> Is there a simple way to get a dictionary of
> argument names and their default values for
> a method or function? I came up with one solution, but
> I feel like Python must have a simpler way.

>>> import inspect
>>> help(inspect.getargspec)
Help on function getargspec in module inspect:

getargspec(func)
    Get the names and default values of a function's arguments.

    A tuple of four things is returned: (args, varargs, varkw, defaults).
    'args' is a list of the argument names (it may contain nested lists).
    'varargs' and 'varkw' are the names of the * and ** arguments or None.
    'defaults' is an n-tuple of the default values of the last n arguments.

>>> def foo(f1, f2, f3, f4="F4", f5="F5"):
...     pass
...
>>> inspect.getargspec(foo)
(['f1', 'f2', 'f3', 'f4', 'f5'], None, None, ('F4', 'F5'))
>>> args, varargs, varkw, defaults = inspect.getargspec(foo)
>>> dict(zip(args[-len(defaults):], defaults))
{'f4': 'F4', 'f5': 'F5'}

>>> class fu:
...         def foo (self, m1, m2, m3, m4='M4', m5='M5'):
...             pass
...
>>> f = fu()
>>> inspect.getargspec(f.foo)
(['self', 'm1', 'm2', 'm3', 'm4', 'm5'], None, None, ('M4', 'M5'))
>>> args, varargs, varkw, defaults = inspect.getargspec(f.foo)
>>> dict(zip(args[-len(defaults):], defaults))
{'m5': 'M5', 'm4': 'M4'}

</F>






More information about the Python-list mailing list