How Can a Program Run Its Own Small Language? The Interpreter Pattern in Python

This article explains how the Interpreter pattern represents grammar rules as classes, how a recursive-descent parser builds the expression tree, how Python's ast module offers a safe alternative to eval, and which pitfalls and costs the pattern carries.

A green tree python coiled tightly around a branch, its head resting among the coils under a narrow beam of light against a dark background.
Photo by Samuel Weissgerber on Unsplash

The present article addresses the Interpreter pattern, which serves programs that must evaluate expressions written by their users, such as pricing formulas, search filters or business rules, without resorting to eval. Strategy games offer a familiar image of the idea: their map editors let designers build triggers by combining small conditions and actions chosen from menus, and the game evaluates those combinations while the match runs. This means that each rule of a small language is represented by a class, a sentence of that language becomes a tree of instances of those classes, and evaluating the sentence consists in asking the root of the tree to interpret itself. The analogy, however, stops at this point, because a trigger editor builds its rules through menus, whereas a text language must first be parsed into a tree, a step that the pattern itself does not describe and that this article adds. Running a language small enough to control completely, with each grammar rule in a class of its own, is the secret weapon of the Interpreter pattern.

Expressions, a Context and a Parser

The pattern distinguishes terminal expressions, such as numbers and variable names, from nonterminal expressions, such as an operation that combines two subexpressions. Evaluation receives a context, here a dictionary of variables, so that the same tree can be evaluated with different values. The tree itself is an instance of the structure described in the article devoted to the Composite pattern, in which leaves and composite nodes share one interface. The following example defines the three node classes, a tokenizer based on a regular expression and a recursive-descent parser, in which each function handles one level of precedence.

import operator
import re
from dataclasses import dataclass


@dataclass(frozen=True)
class Num:
    value: float

    def interpret(self, context):
        return self.value


@dataclass(frozen=True)
class Var:
    name: str

    def interpret(self, context):
        return context[self.name]


@dataclass(frozen=True)
class BinOp:
    op: str
    left: object
    right: object
    OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}

    def interpret(self, context):
        return self.OPS[self.op](self.left.interpret(context), self.right.interpret(context))


TOKEN = re.compile(r"\s*(?:(\d+(?:\.\d+)?)|([A-Za-z_]\w*)|(\S))")


class Parser:
    def __init__(self, text):
        self.tokens = []
        for number, name, symbol in TOKEN.findall(text):
            if number:
                self.tokens.append(("num", float(number)))
            elif name:
                self.tokens.append(("name", name))
            elif symbol:
                self.tokens.append(("op", symbol))
        self.position = 0

    def peek(self):
        return self.tokens[self.position] if self.position < len(self.tokens) else ("end", None)

    def take(self):
        token = self.peek()
        self.position += 1
        return token

    def parse(self):
        tree = self.expression()
        if self.peek()[0] != "end":
            raise SyntaxError(f"unexpected {self.peek()[1]!r}")
        return tree

    def expression(self):  # expression := term (('+' | '-') term)*
        node = self.term()
        while self.peek() in (("op", "+"), ("op", "-")):
            node = BinOp(self.take()[1], node, self.term())
        return node

    def term(self):  # term := factor (('*' | '/') factor)*
        node = self.factor()
        while self.peek() in (("op", "*"), ("op", "/")):
            node = BinOp(self.take()[1], node, self.factor())
        return node

    def factor(self):  # factor := number | name | '(' expression ')'
        kind, value = self.take()
        if kind == "num":
            return Num(value)
        if kind == "name":
            return Var(value)
        if (kind, value) == ("op", "("):
            node = self.expression()
            if self.take() != ("op", ")"):
                raise SyntaxError("expected ')'")
            return node
        raise SyntaxError(f"unexpected {value!r}")


rule = Parser("price * (1 + tax) - discount").parse()
print(rule.interpret({"price": 100, "tax": 0.18, "discount": 5}))  # Output: 113.0
print(rule.interpret({"price": 40, "tax": 0.0, "discount": 0}))    # Output: 40.0
print(Parser("2 + 3 * 4").parse().interpret({}))  # Output: 14.0
print(Parser("5 - 2 - 1").parse().interpret({}))  # Output: 2.0
try:
    Parser("2 +").parse()
except SyntaxError as error:
    print(error)  # Output: unexpected None

The rule is parsed once and evaluated with two different contexts, which is the usual division of work: parsing turns text into a tree, and interpretation walks the tree as often as needed. Precedence comes from the structure of the parser, because term binds multiplication more tightly than expression binds addition, and the loops in both functions group operators from the left, so 5 - 2 - 1 yields 2. Adding a new operator requires one entry in the table and, if it has its own precedence, one more parsing function, while the node classes remain unchanged.

An Alternative: Reusing Python's Own Parser

When the small language is a subset of Python expressions, the module ast can perform the parsing, and the interpreter only has to evaluate the nodes it accepts. The function ast.parse with mode="eval" returns a tree of standard nodes, as described in the article devoted to abstract syntax trees, and a match statement with class patterns can dispatch on them, as described in the article devoted to structural pattern matching. The following example evaluates the same rule with a whitelist of node types and rejects everything else.

import ast
import operator

ALLOWED = {ast.Add: operator.add, ast.Sub: operator.sub,
           ast.Mult: operator.mul, ast.Div: operator.truediv}


def evaluate(text, context):
    def visit(node):
        match node:
            case ast.Expression(body=body):
                return visit(body)
            case ast.Constant(value=int() | float() as value):
                return value
            case ast.Name(id=name):
                return context[name]
            case ast.BinOp(left=left, op=op, right=right) if type(op) in ALLOWED:
                return ALLOWED[type(op)](visit(left), visit(right))
            case _:
                raise ValueError(f"unsupported syntax: {type(node).__name__}")
    return visit(ast.parse(text, mode="eval"))


print(evaluate("price * (1 + tax) - discount", {"price": 100, "tax": 0.18, "discount": 5}))
# Output: 113.0
try:
    evaluate("__import__('os').getcwd()", {})
except ValueError as error:
    print(error)  # Output: unsupported syntax: Call
try:
    ast.literal_eval("2 * 3")
except ValueError:
    print("literal_eval rejects operators")  # Output: literal_eval rejects operators

The call to __import__ is parsed but never executed, because the evaluator recognizes only constants, names and four arithmetic operators; eval would have run it. The function ast.literal_eval is not a substitute, since it accepts only literals and container displays, and its documentation warns that even small inputs can exhaust memory or the C stack. Since Python 3.14, constants are represented only by ast.Constant, because the old classes ast.Num and ast.Str were removed, so evaluators written against them must be updated.

Pitfalls of the Interpreter Pattern

An interpreter executes a tree built from external text, so its pitfalls come from the grammar, from the data that the text refers to and from the cost of walking the tree. Six pitfalls are distinguished, which are the following:

  1. Wrong associativity. A parser that recurses to the right groups 5 - 2 - 1 as 5 - (2 - 1), which yields 4 instead of 2.
  2. Missing variables. A name that the context does not define raises KeyError during evaluation, not during parsing, unless the parser validates names against a known set.
  3. Deep trees. A recursive interpret fails with RecursionError on trees deeper than the recursion limit, which long generated expressions can reach.
  4. Unbounded languages. Each new feature adds classes and grammar rules, so a language that grows conditions, functions and loops becomes a programming language that is better served by a parser generator or by an existing language.
  5. Evaluation cost. Walking a tree of objects calls one method per node, which is slower than executing compiled code.
  6. Parsing on every call. Parsing is far more expensive than evaluation, so text that is parsed each time it is evaluated wastes most of the time.

The first three pitfalls are reproduced in the following example, which builds the trees directly.

import operator
import sys


class Num:
    def __init__(self, value):
        self.value = value

    def interpret(self, context):
        return self.value


class Var:
    def __init__(self, name):
        self.name = name

    def interpret(self, context):
        return context[self.name]


class Sub:
    def __init__(self, left, right):
        self.left, self.right = left, right

    def interpret(self, context):
        return operator.sub(self.left.interpret(context), self.right.interpret(context))


left_grouped = Sub(Sub(Num(5), Num(2)), Num(1))
right_grouped = Sub(Num(5), Sub(Num(2), Num(1)))
print(left_grouped.interpret({}), right_grouped.interpret({}))  # Output: 2 4

try:
    Sub(Var("total"), Num(1)).interpret({"totl": 3})
except KeyError as error:
    print("missing variable:", error)  # Output: missing variable: 'total'

deep = Num(0)
for _ in range(sys.getrecursionlimit() + 100):
    deep = Sub(deep, Num(1))
try:
    deep.interpret({})
except RecursionError:
    print("tree too deep")  # Output: tree too deep

On CPython 3.12, evaluating the tree of price * (1 + tax) - discount took about 310 nanoseconds, against 225 for the same tree compiled into nested closures and 167 for eval of precompiled Python code, whereas parsing the text and then interpreting it took about 5.5 microseconds. The interpretation itself is therefore acceptable for rules evaluated thousands of times, provided that each rule is parsed once and its tree is kept.

Choosing How to Evaluate User Expressions

Consequently, the Interpreter pattern suits small, stable languages whose rules are evaluated many times, while larger or more open requirements call for other tools, as the following table summarizes.

Situation Recommended approach
Arithmetic or boolean rules with a fixed grammar Interpreter pattern with a recursive-descent parser
A subset of Python expressions ast.parse with a whitelist evaluator
Literal data such as numbers, lists and dictionaries ast.literal_eval on trusted input
Rules evaluated very often Parse once, keep the tree, or compile it into closures
A growing language with statements and functions A parser generator or an embedded existing language
Untrusted input of any kind Never eval; a whitelist of node types and limits on length and depth

Conclusion

It is concluded that the Interpreter pattern represents each grammar rule as a class, that a sentence becomes a tree of those objects evaluated against a context, and that parsing, precedence and associativity belong to a separate parser that the pattern presupposes. This magic remains safe only while the language remains small: missing names, deep trees and the cost of parsing must be handled explicitly, and eval is never the shortcut. Making a class subscriptable, so that annotations such as Box[int] can be written for it through the method __class_getitem__, is the subject of a future article of this series.