In which I implement the visitor pattern in Python with decorators.
Tuesday :: 03 January 2012
I’m a fan of the visitor pattern for its emulation of dynamic dispatch and its
ability to extend functionality of a tree of objects.
UPDATE (20 June 2013)
I messed up some in this post. A kind person in Spain helped me figure that out.
You can find the new post and code at
Follow-Up to Python Visitor.
Back to the original article…
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)]