Visitor Pattern in Python
Add a new operation, such as calculating total area, to a set of classes without editing those classes.
- Elements with accept(visitor)
- Visitors with one method per element type
- Double dispatch
PriceVisitortotal = 15Book().accept()visit_book → 10Movie().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.
item.accept(visitor)🚪 The shop lets the inspector invisitor.visit_book(self)🏷️ It says what kind of shop it isPriceVisitor🧾 The inspector with the rules15💰 The total for a book and a movieThe 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
Book.acceptcallsvisitor.visit_book(self);Movie.acceptcallsvisitor.visit_movie(self).PriceVisitorholds the pricing rules for both types.sum(item.accept(visitor) for item in [Book(), Movie()])adds 10 and 5.- A new operation, such as tax, would be a new visitor class without changing
BookorMovie.
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.singledispatchis simpler.
Example code
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()]))
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.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Calling the wrong visitor method
An element must call the method for its own type, or it gets the wrong rules.
class Movie:
def accept(self, visitor): return visitor.visit_book(self)
class Movie:
def accept(self, visitor): return visitor.visit_movie(self)
Finished this lesson?
Mark it as learned to track your progress.