Howto get the argument defaults of a function using an AST-object?

stefan at mayr-stefan.de stefan at mayr-stefan.de
Tue Jul 4 07:22:15 EDT 2006


Hi,

for a school project I'm trying to analyze some python modules. I just
struggeld over a little detail I cannot solve:

shortened example of walking trough an AST with my own visitor:

class MyVisitor:
    def visitFunction(self, t):
        # Here I do not know know how to associate the default values
in t.defaults
        # with the arguments in t.argnames
        params = '???' # howto join the right args with their
default???
        print "def %s(%s)" % (t.name, params)

fname = 'test.py'
ast = compiler.parseFile(fname)
compiler.walk(ast, MyVisitor())

I can only get a list with the arguments or the defaults. The following
examples would return the same:

def foo(x, y=True)
def foo(x=True, y)

Anyone an idea?

Thanks,

    Stefan




More information about the Python-list mailing list