how query function args
Alex Martelli
aleaxit at yahoo.com
Fri Mar 30 07:57:46 EST 2001
"Joshua Marshall" <jmarshal at mathworks.com> wrote in message
news:99vvn1$bmh$1 at news.mathworks.com...
> david winkler <winkler at abaqus-sn.com> wrote:
> > I need to query the names and values of a function's keyword arguments.
> > I
> > suspect that there is an easy way to do this but cannot find it. Would
> > someone care to make a suggestion?
>
> func.func_defaults will return a tuple of the default values, but not
> the names of the formals.
func.func_code, the code-object for the function, has most of the
info you want: its co_argcount attribute is the number of arguments
(the ones with defaults are the last len(func.func_defaults) of
them), its co_varnames attribute has the names of local variables
starting with the argument names.
So, the names of arguments which have default values are:
func.func_code.co_varnames[
func.func_code.co_argcount - len(func.func_defaults)
:
func.func_code.co_argcount
]
in the same order as the func.func_defaults.
E.g., if you want name/value tuples (pairs):
def dw(func):
return zip(
func.func_code.co_varnames[
func.func_code.co_argcount - len(func.func_defaults)
:
func.func_code.co_argcount
], func.func_defaults)
It's of course easy to make this into a dictionary or whatever.
Alex
More information about the Python-list
mailing list