Python Design Patterns

Visitor Pattern in Python

Visitor moves an operation into a separate object and uses element dispatch to select the right method.

What is Visitor Pattern?

Visitor moves an operation into a separate object and uses element dispatch to select the right method.

Add operations to an object structure without changing its element classes.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

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()]))

Expected output

15

How it works

PriceVisitor calculates values for different element types without placing pricing logic in those classes.

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 Python IDE →