ASTVisitor

frank at niessink.com frank at niessink.com
Thu Apr 10 10:05:23 EDT 2003


On Thu Apr 10 14:58:36 2003, Peter Maas wrote:
> I am trying to employ ASTVisitor to convert a python expression to
> postfix form. Following the documentation, I created my own visitor
> class with methods called visit<class>, where <class> represents a
> syntax node like And, Or, ...:
> 
[snip]
> 
> only the Expression node was handled, i.e. the code above didn't
> descend down the tree. According to the docs the return value
> of visit... should decide wether to visit the node's subtree but
> my code didn't bother.

I agree the docs aren't very clear. Apparently, you have to restart 
the traversal after each match. Below is an excerpt of some of my 
code that visits python code and translates it into XML:


# from base.py:

import compiler

class Visitor(compiler.visitor.ASTVisitor):
    def walk(self, node):
        compiler.walk(node, self)


# from class_.py:

class ClassVisitor(base.Visitor, mixin.ImportVisitor):
    def __init__(self, doc, sourcefile = None):
        self.doc = doc
        self.sourcefile = sourcefile or pythonfile.PyFile()

    def visitSuperclasses(self, bases):
        superclassVisitor = SuperclassVisitor()
        for base in bases:
            superclassVisitor.walk(base)
            self.doc.insertSuperclass(superclassVisitor.name)

    def visitClass(self, classNode):
        self.doc.insertClass(classNode.name)
        self.visitSuperclasses(classNode.bases)
        self.doc.insertSourceFile(self.sourcefile.path())
        self.walk(classNode.code)

    def visitFunction(self, functionNode):
        visitor = function.FunctionVisitor(self.doc)
        visitor.walk(functionNode)

    def visitAssName(self, assnameNode):
        self.doc.insertClassField(assnameNode.name)


class SuperclassVisitor(base.Visitor, mixin.NameVisitor):
    pass



Hope this helps,

Frank
-- 
"Look," said Arthur, "would it save you a lot of time if I just gave up and 
went mad now?"
	-- Douglas Adams, 'The Hitch Hiker's Guide to the Galaxy'





More information about the Python-list mailing list