parsing ast nodes help to get callfunc values.

Glich Glich.Glich at googlemail.com
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?

file.py is as follows:
_________________________________
def fun1():
    print "Hi"
    fun2()
    fun4()

def fun2():
    pass

def fun4():
    pass

fun1()

_________________________________


The output from running this program (not file.py) 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

Stmt([Pass()])

isinstance false

Func name: fun4
Func line number: 9

Stmt([Pass()])

isinstance false
Traceback (most recent call last):
  File "/home/glich/compi.py", line 15, in <module>
    print "\nFunc name: " + str(func.name)
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 "file.py".

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/file.py")

count = 0

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

	print "\nFunc name: " + str(func.name)		# 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.
	else:
		print "isinstance false"	# This is always called.... but why?!?!?




More information about the Python-list mailing list