getting argument names from a function

Alex Martelli aleaxit at yahoo.com
Tue Jul 10 17:22:11 EDT 2001


"dan" <dan at eevolved.com> wrote in message
news:W9I27.5835$yh2.510569 at weber.videotron.net...
> Actually, that grabs the entire namespace of the function, not just the
> function variables. I haven't found anything in the func_code tree that
> contains only the function argument keys...
    ...
> >> def aFunction(arg1, arg2):
> >>    print arg1, arg2
> >>
> >> is there a way I can get to the arguments of aFunction (i.e. 'arg1' and
> >> 'arg2')?

>>> def aFunction(arg1, arg2):
...     print arg1, arg2
...
>>> dir(aFunction)
['__dict__', '__doc__', '__name__', 'func_closure', 'func_code',
'func_defaults'
, 'func_dict', 'func_doc', 'func_globals', 'func_name']
>>> aFunction.func_code.co_varnames
('arg1', 'arg2')

If the function has both arguments and other local variables, the arguments
come first in ...co_varnames.  ...co_argcount is the number of arguments.
So:

def argsof(f):
    co = f.func_code
    return co.co_varnames[:co.co_argcount]

should be what you want.


Alex






More information about the Python-list mailing list