parsing ast nodes help to get callfunc values.

Glich Glich.Glich at
Tue Oct 30 20:27:48 CET 2007

Hi! This is my code so far:

This code analyzes a python file.

How can I separate CallFunc from the est of the ast node? is as follows:
def fun1():
    print "Hi"

def fun2():

def fun4():



The output from running this program (not is:
Func name: fun1
Func line number: 1

Stmt([Printnl([Const('Hi')], None), Discard(CallFunc(Name('fun2'), [],
None, None)), Discard(CallFunc(Name('fun4'), [], None, None))])

isinstance false

Func name: fun2
Func line number: 6


isinstance false

Func name: fun4
Func line number: 9


isinstance false
Traceback (most recent call last):
  File "/home/glich/", line 15, in <module>
    print "\nFunc name: " + str(
AttributeError: Discard instance has no attribute 'name'


Please note the traceback is not important right now. I can deal with
that on my own.

What I want to do is sepperate "CallFunc(Name('fun2'), [], None,
None)" from each "func.code" and furthermore to get "fun2" from
"CallFunc(Name('fun2'), [], None, None)" (my ultimate goal!).

I gues I could split the string but I need to be able to get
"CallFunc(Name(****)" from "func.code" which might have multiple
"CallFunc(Name(****)" such as:

"Stmt([Printnl([Const('Hi')], None), Discard(CallFunc(Name('fun2'),
[], None, None)), Discard(CallFunc(Name('fun4'), [], None, None))])"

which is an "ast" repesentation of the function "fun1" in "".

If some one could show me how to use something called "visitor"? I
would be very grateful. I did not understand the documentation and I
am in need of more SIMPLE example code. Any way, thanks.

Is there somthing along the lines of:

>>> first_callfunc = func.code.callfunc(1)
>>> second_callfunc = func.code.callfunc(2)
>>> third_callfunc = func.code.callfunc(3)
>>> print first_callfunc
CallFunc(Name('fun2'), [], None, None)


import compiler
import compiler.ast

parse_file = compiler.parseFile("/home/glich/")

count = 0

for count, func in enumerate(parse_file.node.nodes):

	print "\nFunc name: " + str(		# Prints function name.
	print "Func line number: " + str(func.lineno) + "\n"

	print str(func.code) + "\n"

	if isinstance(func, compiler.ast.CallFunc):
		print "isinstance true"         # This should be called sometimes.
		print "isinstance false"	# This is always called.... but why?!?!?

More information about the Python-list mailing list