On Nov 14, 3:04 am, Aaron Brady <[EMAIL PROTECTED]> wrote: > On Nov 13, 7:16 pm, Alex_Gaynor <[EMAIL PROTECTED]> wrote: > > > I'm trying to figure out what the best architecture for doing code > > generation would be. I have a set of ASTs that define a program, so > > what should I do to for code generation. As I see it the 2 choices > > are to have the ASTs have a generate code method that returns the > > correct code for themselves, or to have a seperate class that > > generates code for a given AST. The problem with the first is that it > > isn't very flexible if I want to generate code for a new language/ > > platform, as well as the fact that it is very tightly coupled. > > However the issue with the other approach is that I can't think of a > > good way to write it without have a ton of if isinstance() calls. Any > > thoughts on what the best appraoch would be? > > I think you are seeking the Visitor Pattern. > > class A: > def meth( self, visitor ): > visitor.visit_classA( self ) > > class B: > def meth( self, visitor ): > visitor.visit_classB( self ) > > class Visitor: > def visit_classA( self, objinst ): > #handle classA > def visit_classB( self, objinst ): > #handle classB > > then A().meth( v ) gets around to getting v.visit_classA called. The > code is moderately repetitive. I believe the Transformer class in the > 'ast' module uses the visitor pattern, possibly called NodeWalker or > something.
Ah this is great, the Visitor class knows how to transform everything into code, and each AST knows which method it is on the Visitor, thanks a ton! -- http://mail.python.org/mailman/listinfo/python-list