BP11 - Mini Calculator (Interpreter) - Learn Design Pattern From Simple Things
Turn nested text formulas like (x + 10) - (y + 2) into an expression tree that evaluates itself. Learn the Interpreter pattern in Python.

Mini Calculator (Interpreter) is a behavioral design pattern: 🖤🖤🤍🤍🤍 (Python usefulness: 2/5)
What is Mini Calculator (Interpreter)?
Interpreter gives a tiny custom language (or rule syntax) a set of grammar classes so an expression can evaluate itself recursively against a context dictionary.
Think of a mini calculator evaluating (x + 10) - (y + 2) where x = 5 and y = 3:
- Terminal expressions (
Number,Variable): leaf nodes that return a number directly or look up a variable name incontext. - Non-terminal expressions (
Add,Subtract): branch nodes that call.interpret(context)on their left and right children, then combine the results.
Why use Interpreter?
- Clean nested evaluation: Once built into a tree (an Abstract Syntax Tree), arbitrarily nested rules like
((x + 10) - (y + 2))evaluate themselves cleanly without fragile string-splitting hacks. - Easy grammar tweaks: Adding a
Multiplyexpression is just one new class without touchingAddorSubtract. - Trade-off: Every grammar rule becomes a class. Once your language grows beyond a handful of rules, hand-written Interpreter classes turn into an unmaintainable pile of boilerplate.
Question: I hate the Interpreter pattern, what are the alternatives in Python?
Answer: In real Python projects, almost nobody hand-writes GoF Interpreter trees. For safe Python literals, use ast.literal_eval(). For custom DSLs, formulas, or query languages, use a real parser library like lark, pyparsing, or Python’s built-in ast module with a safe node visitor.
When to use Interpreter?
Question: When should I use Interpreter?
Answer: When you have a tiny, well-defined rule engine or expression grammar (like search filters, pricing rules, or a mini calculator) that gets evaluated repeatedly against changing context data.
Input:
You have expressions combining numbers, variables (x, y), addition, and subtraction, evaluated against context = {"x": 5, "y": 3}.
from abc import ABC, abstractmethod
class Expression(ABC):
@abstractmethod
def interpret(self, context: dict[str, int]) -> int:
pass
Expected Output:
Evaluating (x + 10) - (y + 2) with x = 5, y = 3 and then with x = 20, y = 4:
Result (x=5, y=3): 10
Result (x=20, y=4): 24
How to implement Interpreter?
Non-Interpreter implementation:
Trying to split strings with if/elif works for "5 + 10", then immediately falls apart as soon as parentheses or nested sub-expressions show up.
def naive_eval(expr: str, context: dict[str, int]) -> int:
tokens = expr.split()
if len(tokens) != 3:
raise ValueError(f"Unsupported nested expression: {expr}")
def resolve(token: str) -> int:
return context[token] if token in context else int(token)
left, op, right = resolve(tokens[0]), tokens[1], resolve(tokens[2])
if op == "+":
return left + right
if op == "-":
return left - right
raise ValueError(f"Unknown operator: {op}")
if __name__ == "__main__":
print(naive_eval("x + 10", {"x": 5}))
try:
print(naive_eval("(x + 10) - (y + 2)", {"x": 5, "y": 3}))
except ValueError as err:
print(f"Error: {err}")
Interpreter Implementation:
from abc import ABC, abstractmethod
class Expression(ABC):
@abstractmethod
def interpret(self, context: dict[str, int]) -> int:
pass
class Number(Expression):
def __init__(self, value: int):
self.value = value
def interpret(self, context: dict[str, int]) -> int:
return self.value
class Variable(Expression):
def __init__(self, name: str):
self.name = name
def interpret(self, context: dict[str, int]) -> int:
return context[self.name]
class Add(Expression):
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: dict[str, int]) -> int:
return self.left.interpret(context) + self.right.interpret(context)
class Subtract(Expression):
def __init__(self, left: Expression, right: Expression):
self.left = left
self.right = right
def interpret(self, context: dict[str, int]) -> int:
return self.left.interpret(context) - self.right.interpret(context)
if __name__ == "__main__":
# Build the expression tree for: (x + 10) - (y + 2)
expression = Subtract(
Add(Variable("x"), Number(10)),
Add(Variable("y"), Number(2)),
)
print(f"Result (x=5, y=3): {expression.interpret({'x': 5, 'y': 3})}")
print(f"Result (x=20, y=4): {expression.interpret({'x': 20, 'y': 4})}")
Once the expression tree is built, you can evaluate the exact same formula repeatedly with different context dictionaries without re-parsing anything. In real Python systems, combine this AST mindset with lark or Python’s built-in ast module rather than hand-coding huge class hierarchies.
Series navigation: Previous: BP10 - Mediator
Related posts
- Software Craft
BP10 - Mediator - Learn Design Pattern From Simple Things
Students don't message every classmate one by one - they broadcast through a central loudspeaker. Learn the Mediator pattern in Python.
4 min readRead → - Software Craft
BP9 - File History - Learn Design Pattern From Simple Things
Undo snapshots look simple on the surface, but how do they work internally? Learn the Memento pattern from simple editing software.
4 min readRead → - Software Craft
BP8 - Visitor - Learn Design Pattern From Simple Things
A spy visits locked-down facilities and extracts different secrets without modifying the target classes. Learn the Visitor pattern in Python.
4 min readRead → - Software Craft
BP7 - Template Method - Learn Design Pattern From Simple Things
Volkswagen shares the same car assembly skeleton across Lamborghini and Porsche while customizing engines and chassis. Learn the Template Method pattern in Python.
4 min readRead →