More Visitor (in Python)

Right after writing the previous post on the Visitor pattern in Python I picked up another paper on the same topic, Visitor Combination and Traversal Control. Of course this one also used Java for its examples, so once again I decided to use Python to explore the ideas presented.

The first part of the paper is all about writing small visitors that then are combined into more complicated ones. This part is nice but not that exciting. The interesting bit is when it gets to controlling traversal, which means it’s possible to remove the traversal code that usually appear in the accept method each visited type has to implement. Let’s see how that can look in Python.

The full code in this post is available at https://gist.github.com/magthe/beddad5c627946f28748.

First we need a structure to traverse, a simple tree will do.

But before this we really should define Visitor, the base class for visitors, and Visitable, the base class of everything that can be visited.

We’ll throw in a visitor for printing the whole tree too:

Due to the lack of traversal in the accept methods it’s easy to be underwhelmed by the Print visitor:

To address this we first need a visitor combinator that runs two visitors in sequence. Unsurprisingly we’ll call it Sequence. Its constructor takes two visitors, and for each node in the tree it passed each one to the node.accept method.

The next building block is a visitor that descends one level down from a Tree node.

At this point it’s worth noting that the name All probably isn’t very well chosen, since we don’t really get all nodes:

We only descend one level, but we still keep the name since that’s the name they use in the paper.

With this in place it does become possible to create combinations that do traverse the full tree though. It even becomes rather simple. Traversing top-down is a simple matter of using a sequence that ends with All, and bottom-up is a matter of using a sequence starting with All.

First top-down:

Then bottom-up:

That’s all rather cute I think.

⟸ Dealing with Microsoft Products, or Battling Loss of Gumption Moving to Hakyll ⟹
Leave a comment