BehavioralPythonverifiedVerified

Visitor Pattern in Python

Lets you add new operations to an object structure without modifying the objects themselves, by separating the algorithm from the object structure it operates on.

How to Implement the Visitor Pattern in Python

1Step 1: Define shape classes and use match/case for visitor dispatch

import math
from dataclasses import dataclass
from typing import Protocol


@dataclass
class Circle:
    radius: float


@dataclass
class Rectangle:
    width: float
    height: float


@dataclass
class Triangle:
    base: float
    height: float
    side_a: float
    side_b: float


Shape = Circle | Rectangle | Triangle

2Step 2: Implement visitors as functions using structural pattern matching

def area(shape: Shape) -> float:
    match shape:
        case Circle(radius=r):
            return math.pi * r ** 2
        case Rectangle(width=w, height=h):
            return w * h
        case Triangle(base=b, height=h):
            return 0.5 * b * h


def perimeter(shape: Shape) -> float:
    match shape:
        case Circle(radius=r):
            return 2 * math.pi * r
        case Rectangle(width=w, height=h):
            return 2 * (w + h)
        case Triangle(base=b, side_a=a, side_b=c):
            return b + a + c

3Step 3: Apply visitors to a collection of shapes

shapes: list[Shape] = [Circle(5), Rectangle(4, 6), Triangle(3, 4, 3, 5)]

print("Areas:", [area(s) for s in shapes])
print("Perimeters:", [perimeter(s) for s in shapes])

Visitor Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Visitor Pattern in the Real World

Think of a tax auditor visiting different types of businesses—a restaurant, a law firm, a retail shop. The auditor (visitor) knows exactly what to examine at each type of business and applies the appropriate inspection procedure. The businesses (elements) simply let the auditor in; they don't change their own operations to accommodate the audit.