Getting callfunc from ast code.

Paul Boddie paul at boddie.org.uk
Sun Oct 28 14:52:52 EDT 2007


On 28 Okt, 19:09, Glich <Glich.Gl... at googlemail.com> wrote:
> """Hi, how can I extend the code shown below so that I can identify
> any "CallFunc" in "func.code" and identify the value of "node" in
> "CallFunc"? Thanks.
>
> This is my code so far:
> """

I tend to use isinstance to work out what kind of AST node I'm looking
at, although I often use the visitor infrastructure to avoid doing
even that.

> """ Given a python file, this program prints out each function's name
> in that file, the line number and the ast code of that function.
>
> """
>
> import compiler
> import compiler.ast
>
> parse_file = compiler.parseFile("/home/glich/file.py")
>
> count = 0
>
> while count < (len(parse_file.node.nodes) - 1):
>
>         func = parse_file.node.nodes[count]

A quick style tip here: it's easier to iterate over the nodes, and if
you want a counter, use the enumerate built-in function. Together with
the above advice...

for count, func in enumerate(parse_file.node.nodes):
    if isinstance(func, compiler.ast.CallFunc):
        ...

>         print "\nFunc name: " + str(func.name)
>         print "Func line number: " + str(func.lineno) + "\n"
>
>         print str(func.code) + "\n"

Take a look at the help text for enumerate to see how I arrived at the
above:

help(enumerate)

Paul




More information about the Python-list mailing list