Skip to main content

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.

Prompt
Write a Python program with the Interpreter pattern: Number, Add and Subtract dataclass nodes that each know how to interpret themselves, and a parse function that turns a string like "3 + 4 - 2" into an expression tree left to right. Interpret the expression and print the equation with its result.
Output: complete Python program

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.