Python Design Patterns

Visitor Pattern in Python

Add a new operation, such as calculating total area, to a set of classes without editing those classes.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • Elements with accept(visitor)
  • Visitors with one method per element type
  • Double dispatch
PriceVisitor
  • PriceVisitortotal = 15
    • Book().accept()visit_book → 10
    • Movie().accept()visit_movie → 5

The operation lives in the visitor

The problem

You have a stable set of classes, such as shapes or products, and keep adding new operations: total price, tax, export to JSON. Adding each operation as a method in every class spreads one feature across many files.

Think of it like this

The Visitor pattern is like a tax inspector visiting different shops. Each shop simply lets the inspector in and says what kind of shop it is. The inspector carries the rules for every kind of shop, so new rules mean a new inspector, not changes to every shop.

From a tax inspector to code
item.accept(visitor)🚪 The shop lets the inspector in
visitor.visit_book(self)🏷️ It says what kind of shop it is
PriceVisitor🧾 The inspector with the rules
15💰 The total for a book and a movie
The operation lives in the visitor, not in the element classes.
In one sentence

The Visitor pattern moves an operation out of a group of element classes into a separate visitor object; each element calls the visitor method that matches its own type.

Key points

  1. Book.accept calls visitor.visit_book(self); Movie.accept calls visitor.visit_movie(self).
  2. PriceVisitor holds the pricing rules for both types.
  3. sum(item.accept(visitor) for item in [Book(), Movie()]) adds 10 and 5.
  4. A new operation, such as tax, would be a new visitor class without changing Book or Movie.

When should you use it?

  • Many operations over a stable set of types: pricing, exporting, drawing.
  • Walking structures such as syntax trees in compilers.
  • Keeping one feature's code in one place.

When not to use it

  • New element types are added often: every visitor must then be updated.
  • Python code where a dictionary of functions per type or functools.singledispatch is simpler.

Example code

Run code →
main.py
class Book:
    # Visitor: move new operations outside stable element classes.
    def accept(self, visitor): return visitor.visit_book(self)


class Movie:
    def accept(self, visitor): return visitor.visit_movie(self)


class PriceVisitor:
    def visit_book(self, book): return 10
    def visit_movie(self, movie): return 5


# Each element dispatches to the matching visitor method.
visitor = PriceVisitor()
print(sum(item.accept(visitor) for item in [Book(), Movie()]))
Get a Run button for this example

Result of running the code

15

Code explanation

Book and Movie each have an accept method that calls the visitor method for their own type. PriceVisitor contains the prices for both, so the pricing logic lives in one class. The generator expression calls accept on each item with the same visitor and adds the results, 10 + 5 = 15.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Calling the wrong visitor method

An element must call the method for its own type, or it gets the wrong rules.

Problem
class Movie:
    def accept(self, visitor): return visitor.visit_book(self)
Fix
class Movie:
    def accept(self, visitor): return visitor.visit_movie(self)

Finished this lesson?

Mark it as learned to track your progress.