Visitor Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Visitor Pattern runs in O(n) time and O(n) space, in Python as in every other language.
- ✓functools.singledispatch gives genuine dispatch on the runtime type of the first argument, registering an implementation per type and resolving through the method resolution order, so it replaces the accept bounce entirely.
- ✓Use singledispatch for a visitor over an open set of types and match for a closed one; a reviewer will not expect accept methods on the nodes in either case.
- ✓The Python trap: singledispatch dispatches on the FIRST argument only, so a visitor that wants to vary on both the node and a context object cannot express the second dimension, and people discover this after building on it.
- ✓singledispatch caches the resolved implementation per concrete type in a dictionary keyed by class, so after the first call for a given type dispatch is one lookup, comparable to a normal method call.
What Visitor Pattern actually is
Visitor Pattern in Python: what you actually reach for
Python implementation
from functools import singledispatch
from dataclasses import dataclass
@dataclass
class Num: value: float
@dataclass
class Add: left: object; right: object
@dataclass
class Mul: left: object; right: object
# Real dispatch on the argument type: NO accept() method on the nodes.
@singledispatch
def evaluate(node) -> float:
raise TypeError(f"no evaluator for {type(node).__name__}")
@evaluate.register
def _(node: Num) -> float: return node.value
@evaluate.register
def _(node: Add) -> float: return evaluate(node.left) + evaluate(node.right)
@evaluate.register
def _(node: Mul) -> float: return evaluate(node.left) * evaluate(node.right)
evaluate(Add(Num(1), Mul(Num(2), Num(3)))) # 7.0
# The match form, for a closed set:
def show(node) -> str:
match node:
case Num(value=v): return str(v)
case Add(left=l, right=r): return f"({show(l)} + {show(r)})"
case Mul(left=l, right=r): return f"({show(l)} * {show(r)})"
case _: raise TypeError(node)
# singledispatch cannot express a Protocol or a subscripted generic:
# @evaluate.register
# def _(node: list[int]) -> float: ... # never matchesThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Visitor Pattern?
functools.singledispatch gives genuine dispatch on the runtime type of the first argument, registering an implementation per type and resolving through the method resolution order, so it replaces the accept bounce entirely. functools.singledispatchmethod is the version for methods, where dispatch happens on the first argument after self. The match statement, from 3.10, supports class patterns that match a node type and destructure its attributes in one line, which is the other idiomatic form. ast.NodeVisitor in the standard library is a hand-rolled visitor worth reading.
What is the most common Python mistake when implementing Visitor Pattern?
singledispatch dispatches on the FIRST argument only, so a visitor that wants to vary on both the node and a context object cannot express the second dimension, and people discover this after building on it. It also dispatches on the runtime class, so it does not understand typing constructs: registering for a Union, a Protocol or a parameterised generic either raises or silently never matches. Since 3.11 unions in the annotation are supported, but Protocol and subscripted generics still are not, and the failure is a dispatch that quietly falls through to the base implementation.
How does Visitor Pattern actually perform in Python?
singledispatch caches the resolved implementation per concrete type in a dictionary keyed by class, so after the first call for a given type dispatch is one lookup, comparable to a normal method call. That cache is invalidated whenever a new implementation is registered or the class hierarchy changes, so registering inside a loop repeatedly clears it. A match statement with class patterns compiles to a sequence of isinstance checks, so it is linear in the number of cases and worth ordering by frequency. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.