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

S

stefan

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
 
F

Fredrik Lundh

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)

the latter is a syntax error.
Anyone an idea?

the defaults array contains the defaults for the len(defaults) last arguments.

</F>
 
S

stefan

Fredrik said:
....

the latter is a syntax error.
...

the defaults array contains the defaults for the len(defaults) last arguments.

And again the own stupidity: I didn't check all my testcases for syntax
errors.

Thanks a lot,

Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top