In lanugages that do not support method overloading, the visitor pattern tends
to fall apart. Python is one of those languages. So, in an effort to have the
same effect in Python, here’s some code that does that. I’m just amazed at how
few lines it takes to create this effect.
def__call__(self, *args, **kw): typ = type(args[self.param_index]) d = self.targets.get(typ) if d isnotNone: return d(*args, **kw) else: issub = issubclass t = self.targets ks = t.iterkeys() return [t[k](*args, **kw) for k in ks if issub(typ, k)]
We can use it in the following way. Imaginge we have an abstract syntax tree
with nodes that accept a visitor. The following code would correctly print an
infix assignment expression.
classAbstractSyntaxTreeVisitor(object): @visit.on('node') defvisit(self, node): """ This is the generic method that initializes the dynamic dispatcher. """
@visit.when(BaseNode) defvisit(self, node): """ Will run for nodes that do specifically match the provided type. """ print"Unrecognized node:", node
@visit.when(AssignmentExpression) defvisit(self, node): """ Matches nodes of type AssignmentExpression. """ node.children[0].accept(self) print'=' node.children[1].accept(self)