Adding Operations Without Editing Classes: The Visitor Pattern in Python

This article explains how the Visitor pattern adds operations over a family of classes without editing them, and compares double dispatch with name-based dispatch and singledispatchmethod in Python.

A bright green snake coiled around a branch among dark leaves, its mouth open beside the bark of a tree
Photo by Robin McSkelly on Unsplash

A structure of objects of several types, such as the shapes of a drawing or the nodes of a syntax tree, usually needs many unrelated operations: computing areas, exporting, validating, rendering. The present article examines the Visitor pattern, which places each operation in a separate class and leaves the element classes unchanged, and it compares the classic form based on double dispatch with the forms that Python makes simpler: dispatch by method name, as in the module ast, and functools.singledispatchmethod. It also shows who is responsible for walking a nested structure, demonstrates a difference in how the alternatives treat subclasses, and describes when the pattern is the wrong choice. Adding an operation over a whole family of classes by writing one new class, without editing any of the existing ones, is the secret weapon of the Visitor pattern.

Double Dispatch: accept and visit

In strategy games, an engineer unit that enters a building produces an effect that depends on both the unit and the building: it repairs a friendly bunker and captures an enemy factory. The classic Visitor reproduces this double dependency: each element class implements accept, which calls the method of the visitor that corresponds to its own type, so the operation that runs depends on the visitor and on the element. The analogy, however, stops at this point, because a game decides such effects once in its rules, whereas a program can add a new visitor, and therefore a new operation, at any time without touching the elements.

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def accept(self, visitor):
        return visitor.visit_circle(self)

class Square:
    def __init__(self, side):
        self.side = side

    def accept(self, visitor):
        return visitor.visit_square(self)

class Group:
    def __init__(self, *children):
        self.children = children

    def accept(self, visitor):
        return visitor.visit_group(self)

class AreaVisitor:
    def visit_circle(self, circle):
        return math.pi * circle.radius ** 2

    def visit_square(self, square):
        return square.side ** 2

    def visit_group(self, group):
        return sum(child.accept(self) for child in group.children)

class SvgVisitor:
    def visit_circle(self, circle):
        return f'<circle r="{circle.radius}"/>'

    def visit_square(self, square):
        return f'<rect width="{square.side}" height="{square.side}"/>'

    def visit_group(self, group):
        return "<g>" + "".join(child.accept(self) for child in group.children) + "</g>"

drawing = Group(Circle(1), Square(2), Group(Square(3)))
print(round(drawing.accept(AreaVisitor()), 2))  # Output: 16.14
print(drawing.accept(SvgVisitor()))
# Output: <g><circle r="1"/><rect width="2" height="2"/><g><rect width="3" height="3"/></g></g>

The two operations live in two classes, and the shapes know nothing about areas or SVG. The visitor returns values instead of printing them, which lets results combine, and the method visit_group decides how to walk the nested structure: here each visitor traverses the children, although the traversal can also be placed in the elements or in a separate iterator. Adding a third operation, such as a bounding box, means writing one more visitor and editing no shape.

Dispatch by Method Name, Without accept

Python can select the visit method from the name of the element's class, so the elements need no accept method at all. The class ast.NodeVisitor of the standard library works in this way: its method visit looks for a method named visit_ followed by the class name of the node and falls back to generic_visit, the mechanism used in the article devoted to abstract syntax trees.

import math

class Circle:
    def __init__(self, radius):
        self.radius = radius

class Square:
    def __init__(self, side):
        self.side = side

class Visitor:
    def visit(self, node):
        method = getattr(self, "visit_" + type(node).__name__, self.generic_visit)
        return method(node)

    def generic_visit(self, node):
        raise TypeError(f"no visit method for {type(node).__name__}")

class AreaVisitor(Visitor):
    def visit_Circle(self, circle):
        return math.pi * circle.radius ** 2

    def visit_Square(self, square):
        return square.side ** 2

area = AreaVisitor()
print(round(area.visit(Circle(1)), 2), area.visit(Square(2)))  # Output: 3.14 4

The element classes are now plain data, which suits structures that come from a parser or another library and cannot be modified. The price is that the connection between an element and its method rests on a string built at run time, so a renamed class silently stops matching its method.

Dispatch by Type with singledispatchmethod

The decorator functools.singledispatchmethod selects the implementation by the type of the first argument after self, registered through annotations, and it follows the method resolution order, so a subclass reuses the implementation of its parent, as described in the article devoted to singledispatch.

import math
from functools import singledispatchmethod

class Circle:
    def __init__(self, radius):
        self.radius = radius

class Square:
    def __init__(self, side):
        self.side = side

class UnitSquare(Square):
    def __init__(self):
        super().__init__(1)

class AreaVisitor:
    @singledispatchmethod
    def visit(self, node):
        raise TypeError(f"no visit method for {type(node).__name__}")

    @visit.register
    def _(self, circle: Circle):
        return math.pi * circle.radius ** 2

    @visit.register
    def _(self, square: Square):
        return square.side ** 2

area = AreaVisitor()
print(area.visit(UnitSquare()))  # Output: 1

The subclass UnitSquare has no implementation of its own, and the visitor treats it as a Square. For a few types and short operations, a match statement with class patterns offers a third form inside a single function, as shown in the article devoted to structural pattern matching.

Pitfalls of the Visitor Pattern

The pattern makes operations easy to add and element types hard to add, and most of its errors come from forgetting that asymmetry. Six pitfalls are distinguished, which are the following:

  1. New element types. Every existing visitor must receive a method for a new element class, and a forgotten one fails only when that element is visited.
  2. Name-based dispatch ignores inheritance. A subclass has a different name, so visit_ plus the class name does not find the parent's method.
  3. Silent fallbacks. A generic_visit that does nothing hides missing methods; raising an error, or descending into children deliberately, is safer.
  4. Visitors that need private data. Operations outside the classes need access to their attributes, which may push the element classes to expose more than they otherwise would.
  5. Reused stateful visitors. A visitor that accumulates results in attributes carries them into its next use unless it is reset.
  6. Deep structures. Recursive traversal of a very deep tree can exceed the recursion limit; an explicit stack avoids it.

The second pitfall is reproduced in the following example, in contrast with the previous section.

class Square:
    def __init__(self, side):
        self.side = side

class UnitSquare(Square):
    def __init__(self):
        super().__init__(1)

class AreaVisitor:
    def visit(self, node):
        method = getattr(self, "visit_" + type(node).__name__, self.generic_visit)
        return method(node)

    def generic_visit(self, node):
        raise TypeError(f"no visit method for {type(node).__name__}")

    def visit_Square(self, square):
        return square.side ** 2

try:
    AreaVisitor().visit(UnitSquare())
except TypeError as error:
    print(error)  # Output: no visit method for UnitSquare

The method name is built from UnitSquare, not from Square, so the lookup fails even though the subclass is a square in every other respect. A name-based visitor can walk type(node).__mro__ and try each class name in turn, but singledispatchmethod already provides that behaviour.

Choosing a Form of Dispatch

Consequently, the form depends on whether the element classes can be modified, on whether inheritance must be respected and on how many operations exist, as the following table summarizes.

Situation Recommended approach
Many operations over a stable family of classes that can be modified Classic Visitor with accept
Element classes that cannot be modified, such as parser nodes Dispatch by method name, as ast.NodeVisitor
Subclasses must reuse the parent's operation functools.singledispatchmethod
A few types and short operations match with class patterns
Element types change often and operations rarely Ordinary methods on the classes, not Visitor

Conclusion

It is concluded that the Visitor pattern moves each operation over a family of classes into a class of its own, selected by double dispatch through accept or, in Python, by method name or by type, and that this makes new operations cheap and new element types expensive. This magic is best applied to stable structures, such as syntax trees, with visitors that return values, raise on unknown elements and, when inheritance matters, dispatch through singledispatchmethod. Passing a request along a sequence of handlers until one of them accepts it, rather than choosing the handler in advance by type, is the subject of the Chain of Responsibility pattern, which is developed in a future article of this series.