---
title: "BP11 - Mini Calculator (Interpreter) - Learn Design Pattern From Simple Things"
description: "Turn nested text formulas like (x + 10) - (y + 2) into an expression tree that evaluates itself. Learn the Interpreter pattern in Python."
pubDate: "2023-05-09"
lang: "en"
slug: "bp11-interpreter-learn-design-pattern-from-simple-things"
url: "https://hoangyell.com/bp11-interpreter-learn-design-pattern-from-simple-things/"
author: "HoangYell"
translation_vi: "https://hoangyell.com/vi/bp11-interpreter-learn-design-pattern-from-simple-things/"
categories: ["Software Craft"]
tags: ["design-patterns", "behavioral-patterns"]
heroImage: "https://raw.githubusercontent.com/HoangGeek/store/main/webp/ai-bp11-interpreter-learn-design-pattern-from-simple-things-hero.webp"
---

_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 in `context`.
- **Non-terminal expressions** (`Add`, `Subtract`): branch nodes that call `.interpret(context)` on their left and right children, then combine the results.

```markdy
scene duration=18 layout=TB width=760 height=960
theme: light=doodle dark=nebula

user Ctx "context = {'x': 5, 'y': 3}"
service Root "Subtract (left - right)" icon=python
service Left "Add (x + 10)"
service Right "Add (y + 2)"
storage Leaves "Variable('x')=5, 10 | Variable('y')=3, 2"

beat eval "1. Evaluate leaves against context":
  show $nodes stagger=50ms
  Ctx -> Leaves "Lookup x=5, y=3"
  Leaves -> Left "5 + 10 = 15"
  Leaves -> Right "3 + 2 = 5"
  glow Leaves color=#3b82f6

beat combine "2. Reduce up the AST":
  Left -> Root "15"
  Right -> Root "5"
  Ctx <- Root "15 - 5 = 10"
  glow Root color=#22c55e

player:
  playback:
    loop true
  controls:
    speed true
    speeds "0.25"
    interact true
    fullscreen true
    gif true
    theme true
  interaction:
    zoom true
    pan true
    click_to_play true
    double_click_to_reset true
    keyboard false
  chrome:
    badge true
    progress none
```

## 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 `Multiply` expression is just one new class without touching `Add` or `Subtract`.
- **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}`.

```python
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`:

```shell
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.

```python
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:

```python
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](https://hoangyell.com/bp10-mediator-learn-design-pattern-from-simple-things/)
