how to find a function definition using AST
Robert Brewer
fumanchu at amor.org
Mon Feb 23 12:33:42 EST 2004
Stephen Emslie wrote:
> I am using the compiler.visitor module to examine a piece of code and
> extract certain useful information. However, I have run into
> trouble that I
> dont know how to solve. When I override visitCallFunc I can
> get the name of
> the function being called, but thats about it. What I would
> really like is
> to know exactly where that function is defined (line of code,
> what class if
> belongs to, everything).
>
> I had a thought that when one prints the node argument from
> visitCallFunc
> then you can see a node which looks something like
> Getattr(Name('catfish'),
> 'double'. Perhaps if this statement could be evaluated then
> the function in
> question could be found.
>
> class MyVisitor(visitor.ASTVisitor):
> def visitCallFunc(self,node):
> print node
Hi Stephen,
You might notice (by looking at compiler.visitor source code) that, if
you define visitCallFunc, you have to continue walking that node on your
own--it isn't done for you. You might modify visitCallFunc to do the
same thing that the default() method does (after your print statement,
perhaps):
def default(self, node, *args):
for child in node.getChildNodes():
self.dispatch(child, *args)
Also, note that a CallFunc Node obtains a set of attributes which other
Nodes don't have:
More information about the Python-list
mailing list