Code generator and visitor pattern

Stefan Behnel stefan_ml at behnel.de
Thu Jul 15 23:33:17 EDT 2010


Carl Banks, 16.07.2010 01:14:
> Around these parts, we consider the main use of most Design Patterns
> to be to work around limitations of other languages.  Visitor Pattern
> is probably the worst example of it.
>
> In Python it's completely unnecessary (at least in its boilerplate-
> heavy incarnation as used in C++), and the fact that Python isn't
> strongly typed, as you put it, is exactly the reason why.
>
> Say you have a bunch of unrelated types that define a calculate
> method, you have a variable x that could be any of these types.
> Here's how you would do that in Python:
>
>      x.calculate()
>
> Bam, that's it.  Visitor Pattern in Python.  You don't have to create
> a bunch of homemade dispatching boilerplate like you do in C++.

Well, you can do that in every OO language. It's not what the visitor 
pattern is there for, though.

The code I referenced is from the Cython compiler, and we use it to "do 
stuff" with the AST. The visitor pattern is actually a pretty common way to 
bind code in a single place that does a certain thing to different parts of 
a data structure. Without it, if you kept that code *inside* of the data 
structure, you'd have to spill the type specific parts all over your code.

Stefan




More information about the Python-list mailing list