Skip to content

Instantly share code, notes, and snippets.

@gvanrossum
Created September 14, 2020 23:25
Show Gist options
  • Save gvanrossum/b2ab40483805d409890ef754f67db4cb to your computer and use it in GitHub Desktop.
Save gvanrossum/b2ab40483805d409890ef754f67db4cb to your computer and use it in GitHub Desktop.
Visitor pattern with match/case
# Compare https://en.wikipedia.org/wiki/Visitor_pattern#Python_example
from dataclasses import dataclass
class CarElement:
def visit(self, func):
func(self)
class Body(CarElement):
pass
class Engine(CarElement):
pass
@dataclass
class Wheel(CarElement):
name: str
class Car(CarElement):
def __init__(self):
self.elements = [
Wheel("front left"), Wheel("front right"),
Wheel("back left"), Wheel("back right"),
Body(), Engine()
]
def visit(self, func):
for element in self.elements:
element.visit(func)
func(self)
def do_car_element(elem):
match elem:
case Body():
print("Moving my body.")
case Car():
print("Starting my car.")
case Wheel(name):
print(f"Kicking my {name} wheel.")
case Engine():
print("Starting my engine.")
def print_car_element(elem):
match elem:
case Body():
print("Visiting body.")
case Car():
print("Visiting car.")
case Wheel(name):
print(f"Visiting {name} wheel.")
case Engine():
print("Visiting engine.")
car = Car()
car.visit(print_car_element)
car.visit(do_car_element)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment