What It Is
The Interpreter pattern evaluates sentences in a small language by building a tree of expression objects — each node knows how to interpret itself. Numbers interpret to themselves; an addition node interprets its two sides and adds them.
It fits small languages: filters, formulas, simple rules. Real languages deserve real parser tools.
Example: A Tiny Calculator
The input 3 + 4 - 2 becomes a tree of Number, Add and Subtract dataclass nodes. One call to interpret() on the root evaluates the whole expression.
Every node interprets itself
parse builds the tree left to right; interpret() walks it. Supporting * would be one new node type — the existing ones stay untouched.
Output: complete Python program
from dataclasses import dataclass
# Every node knows how to interpret itself.
@dataclass
class Number:
value: int
def interpret(self) -> int:
return self.value
@dataclass
class Add:
left: "Expression"
right: "Expression"
def interpret(self) -> int:
return self.left.interpret() + self.right.interpret()
@dataclass
class Subtract:
left: "Expression"
right: "Expression"
def interpret(self) -> int:
return self.left.interpret() - self.right.interpret()
# An expression is any of the three node types.
Expression = Number | Add | Subtract
def parse(source: str) -> Expression:
parts = source.split()
expr: Expression = Number(int(parts[0]))
for i in range(1, len(parts), 2):
number = Number(int(parts[i + 1]))
if parts[i] == "+":
expr = Add(expr, number)
else:
expr = Subtract(expr, number)
return expr
source = "3 + 4 - 2"
print(source, "=", parse(source).interpret())
When to Use It
Use it when users or configs express logic in a small language of your design: search filters, pricing formulas, validation rules.
Skip it when the "language" is three fixed options (use a simple if/elif) — or a real language (use a parser generator or an existing engine).
Pros and Cons
Pros: the grammar maps one-to-one onto small types; new operations are new node types; expression trees can be built, checked and reused.
Cons: grows painful as the grammar grows; parsing itself still has to be written; performance is modest compared to compiled logic.