The Interpreter pattern provides a way to evaluate expressions using a class-based structure. It’s useful for defining and processing a simple language or rule set using code.
When a program needs to evaluate expressions written in a custom syntax—like a small language or set of rules—the logic can get messy. The Interpreter pattern helps by turning each part of the language into a class that knows how to interpret itself, keeping the code organized and easier to manage.
Use this pattern when:
Avoid this pattern if:
Key parts of the pattern include:
{"x": 10, "y": 5}
).interpret()
method that evaluates the expression using the context.Think of a librarian using a library system. Even without knowing each book’s contents, the librarian can find information using a consistent system. Similarly, the Interpreter pattern uses a fixed structure to evaluate various expressions.
Here’s a basic Python example:
# Context stores variable values
context = Context({"x": 10, "y": 5, "z": 2})
# Build an expression: x + (y - z)
expr = Add(Variable("x"), Subtract(Variable("y"), Variable("z")))
# Interpret and evaluate the expression
print("Result:", expr.interpret(context)) # Outputs: 13
In this example:
Variable("x")
is a terminal expression.Add()
and Subtract()
are non-terminal expressions.interpret()
evaluates the full expression using the values in the context.See a full implementation on GitHub: interpreter.py on GitHub