[Tutor] func headline & module inspect

spir ☣ denis.spir at gmail.com
Tue Mar 23 19:33:42 CET 2010


I was looking for a way to get info about func definition, esp. its param list. The aim beeing to reproduce more or less its header line.
Found useful hints at http://stackoverflow.com/questions/582056/getting-list-of-parameters-inside-python-function. Example:

import inspect

def func(a,b,c, d=4,e=5, *items,**params):

argSpec = inspect.getargspec(func)
print argSpec
print inspect.formatargspec(argSpec)
print inspect.getsourcelines(func)

ArgSpec(args=['a', 'b', 'c', 'd', 'e'], varargs='items', keywords='params', defaults=(4, 5))
((a, b, c, d, e), items, params, (4, 5))
(['def func(a,b,c, d=4,e=5, *items,**params):\n', '    pass\n'], 8)

How does inspect do this magic?

print dir(argSpec)
# --> [... 'args', 'count', 'defaults', 'index', 'keywords', 'varargs']

What are (the methods) count and index supposed to provide?


    Get the names and default values of a Python 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 a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

    Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs, keywords, defaults).

Finally, I found extremely complicated to rebuild the func headline:

def namedArguments(argNames,defaultValues):
    (s1,s2) = (len(argNames),len(defaultValues))
    delta = s1 - s2
    defaultExpr = lambda i: '' if i<0 or i>=s2 else "=%s" %(defaultValues[i])
    return ', '.join( "%s%s" %(argNames[i],defaultExpr(i-delta)) for i in range(s1) )
def headLine(f):
    funcName = f.__name__
    argNames, varargName, kwargName, defaultValues = inspect.getargspec(f)
    namedArgs = namedArguments(argNames,defaultValues)
    varargName = '' if varargName is None else ", *%s" %varargName
    kwargName = '' if kwargName is None else ", **%s" %kwargName
    return "%s(%s%s%s)" %(funcName,namedArgs,varargName,kwargName)
print headLine(func)

# ==> func(a, b, c, d=4, e=5, *items, **params)

Maybe I'm overlooking an easier way to do that? (And why not built in the module inspect?)


vit esse estrany ☣


More information about the Tutor mailing list