Python Interpreter Pattern
The Interpreter Pattern is a behavioral design pattern that defines the grammar of a language and establishes an interpreter to interpret sentences in that language. Simply put, it is like a small compiler that can parse and execute expressions following specific grammar rules.
Core idea
Imagine a calculator scenario: when you enter "2 + 3 * 4" such an expression, the calculator needs to understand the meaning of the string and perform the calculation according to mathematical rules. The interpreter pattern is a design solution that implements this process of "understanding" and "execution".
Applicable scenarios
The interpreter pattern is especially suitable for the following situations:
- When a language or expression needs to be interpreted and executed
- The grammar is relatively simple and not overly complex
- Execution efficiency is not a key consideration
- The grammar rules of the language need to be extended frequently
Pattern Structure
Let's understand the core components of the interpreter pattern through a class diagram:

Component Description
AbstractExpression (Abstract Expression)
- Defines the interface for the interpret operation
- Usually contains
interpret()Method
TerminalExpression (Terminal Expression)
- Implements interpret operations related to terminals in the grammar
- Cannot be broken down into smaller expressions
NonterminalExpression (Nonterminal Expression)
- Implements interpret operations related to nonterminals in the grammar
- Usually contains references to other expressions
Context
- Contains some global information needed by the interpreter
- Stores input and output results
Basic Syntax and Implementation
Abstract Expression Class
Example
from
abc
import
ABC
,
abstractmethod
class
Expression
(
ABC
)
:
"""Abstract expression class, defining the interpret interface"""
@
abstractmethod
def
interpret
(
self
,
context
)
:
"""Interpret method, implemented by concrete subclasses"""
pass
Terminal Expression
Example
class
NumberExpression
(
Expression
)
:
"""Number expression - Terminal expression"""
def
init
(
self
,
number
)
:
self
.
number
=
number
def
interpret
(
self
,
context
)
:
Directly returns the numeric value
return
self
.
number
def
str
(
self
)
:
return
f
"Number({self.number})"
Nonterminal Expression
Example
class
AddExpression
(
Expression
)
:
"""Addition expression - Nonterminal expression"""
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
Left expression
self
.
right
=
right
Right expression
def
interpret
(
self
,
context
)
:
Interpret the left and right expressions separately, then add them
return
self
.
left
.
interpret
(
context
)
self
.
right
.
interpret
(
context
)
def
str
(
self
)
:
return
f
"({self.left} + {self.right})"
class
SubtractExpression
(
Expression
)
:
"""Subtraction expression - Nonterminal expression"""
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
self
.
right
=
right
def
interpret
(
self
,
context
)
:
return
self
.
left
.
interpret
(
context
)
self
.
right
.
interpret
(
context
)
def
str
(
self
)
:
return
f
"({self.left} - {self.right})"
class
MultiplyExpression
(
Expression
)
:
"""Multiplication expression - Nonterminal expression"""
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
self
.
right
=
right
def
interpret
(
self
,
context
)
:
return
self
.
left
.
interpret
(
context
)
self
.
right
.
interpret
(
context
)
def
str
(
self
)
:
return
f
"({self.left} * {self.right})"
Complete Example: Simple Calculator
Let's implement a complete simple calculator to interpret mathematical expressions:
Example
class
CalculatorContext:
"""Calculator context, storing calculation-related information"""
def
init
(
self
)
:
self
.
variables
=
{
}
Storing variable values
def
set_variable
(
self
,
name
,
value
)
:
"""Set a variable value"""
self
.
variables
[
name
]
=
value
def
get_variable
(
self
,
name
)
:
"""Get a variable value"""
return
self
.
variables
.
get
(
name
,
0
)
class
VariableExpression
(
Expression
)
:
"""Variable expression - Terminal expression"""
def
init
(
self
,
name
)
:
self
.
name
=
name
def
interpret
(
self
,
context
)
:
Get a variable value from the context
return
context.
get_variable
(
self
.
name
)
def
str
(
self
)
:
return
self
.
name
class
Calculator:
"""Calculator class - Building and interpreting expressions"""
@
staticmethod
def
parse_expression
(
expression_str
,
context
)
:
"""
Parse a string expression into an expression tree
Simplified here; real applications may need a more complex parser
"""
Simple expression parsing (real projects should use a dedicated parsing library)
tokens
=
expression_str.
replace
(
'('
,
' ( '
)
.
replace
(
')'
,
' ) '
)
.
split
(
)
return
Calculator._parse_tokens
(
tokens
)
@
staticmethod
def
_parse_tokens
(
tokens
)
:
"""Recursively parse a list of tokens"""
if
not
tokens:
return
None
token
=
tokens.
pop
(
0
)
if
token
==
'('
:
Start parsing a compound expression
left
=
Calculator._parse_tokens
(
tokens
)
operator
=
tokens.
pop
(
0
)
right
=
Calculator._parse_tokens
(
tokens
)
tokens.
pop
(
0
)
Remove ')'
if
operator
==
'+'
:
return
AddExpression
(
left
,
right
)
elif
operator
==
'-'
:
return
SubtractExpression
(
left
,
right
)
elif
operator
==
'*'
:
return
MultiplyExpression
(
left
,
right
)
else
:
Parse a basic expression (number or variable)
if
token
.
isdigit
(
)
or
(
token
[
0
]
==
'-'
and
token
[
1
:
]
.
isdigit
(
)
)
:
return
NumberExpression
(
int
(
token
)
)
else
:
return
VariableExpression
(
token
)
Usage examples
def
main
(
)
:
Create a context
context
=
CalculatorContext
(
)
context.
set_variable
(
'x'
,
10
)
context.
set_variable
(
'y'
,
5
)
Manually build the expression: (x + 3) * (y - 2)
expression
=
MultiplyExpression
(
AddExpression
(
VariableExpression
(
'x'
)
,
NumberExpression
(
3
)
)
,
SubtractExpression
(
VariableExpression
(
'y'
)
,
NumberExpression
(
2
)
)
)
(
f
"Expression: {expression}"
)
result
=
expression.
interpret
(
context
)
(
f
"Result: {result}"
)
Output: (10 + 3) * (5 - 2) = 39
Using the parser
simple_expr
=
AddExpression
(
NumberExpression
(
5
)
,
NumberExpression
(
3
)
)
(
f
"Simple expression: {simple_expr} = {simple_expr.interpret(context)}"
)
if
name
==
"main"
:
main
(
)
Advanced Application: SQL WHERE Condition Interpreter
Let's look at a more practical example - implementing a simplified SQL WHERE condition interpreter:
Example
class
SQLContext:
"""SQL query context"""
def
init
(
self
,
record
)
:
self
.
record
=
record
Data records
def
get_value
(
self
,
field
)
:
"""Get a field value"""
return
self
.
record
.
get
(
field
)
class
FieldExpression
(
Expression
)
:
"""Field expression"""
def
init
(
self
,
field_name
)
:
self
.
field_name
=
field_name
def
interpret
(
self
,
context
)
:
return
context.
get_value
(
self
.
field_name
)
class
ConstantExpression
(
Expression
)
:
"""Constant expression"""
def
init
(
self
,
value
)
:
self
.
value
=
value
def
interpret
(
self
,
context
)
:
return
self
.
value
class
EqualsExpression
(
Expression
)
:
"""Equality comparison expression"""
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
self
.
right
=
right
def
interpret
(
self
,
context
)
:
return
self
.
left
.
interpret
(
context
)
==
self
.
right
.
interpret
(
context
)
class
AndExpression
(
Expression
)
:
"""AND expression"""
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
self
.
right
=
right
def
interpret
(
self
,
context
)
:
return
self
.
left
.
interpret
(
context
)
and
self
.
right
.
interpret
(
context
)
class
OrExpression
(
Expression
)
:
"""OR expression"""
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
self
.
right
=
right
def
interpret
(
self
,
context
)
:
return
self
.
left
.
interpret
(
context
)
or
self
.
right
.
interpret
(
context
)
Usage Example: Simulating SQL WHERE Condition Filtering
def
sql_demo
(
)
:
Simulated data records
records
=
[
{
'name'
:
'Alice'
,
'age'
:
25
,
'department'
:
'Engineering'
}
,
{
'name'
:
'Bob'
,
'age'
:
30
,
'department'
:
'Sales'
}
,
{
'name'
:
'Charlie'
,
'age'
:
28
,
'department'
:
'Engineering'
}
,
{
'name'
:
'Diana'
,
'age'
:
35
,
'department'
:
'Marketing'
}
]
Build the WHERE condition: (department = 'Engineering') AND (age > 26)
class
GreaterThanExpression
(
Expression
)
:
def
init
(
self
,
left
,
right
)
:
self
.
left
=
left
self
.
right
=
right
def
interpret
(
self
,
context
)
:
return
self
.
left
.
interpret
(
context
)
self
.
right
.
interpret
(
context
)
Build the expression tree
condition
=
AndExpression
(
EqualsExpression
(
FieldExpression
(
'department'
)
,
ConstantExpression
(
'Engineering'
)
)
,
GreaterThanExpression
(
FieldExpression
(
'age'
)
,
ConstantExpression
(
26
)
)
)
(
"Matching records:"
)
for
record
in
records:
context
=
SQLContext
(
record
)
if
condition.
interpret
(
context
)
:
(
f
"- {record['name']}, {record['age']} years old, {record['department']}"
)
if
name
==
"main"
:
sql_demo
(
)
Advantages and Disadvantages of the Pattern
Advantages
- Easy to extend the grammar: Add new expression classes to extend the grammar rules
- Easy to implement: Each expression class is relatively simple, easy to implement and maintain
- Highly flexible: The way of interpretation can be changed dynamically
- Follows the Open/Closed Principle: open for extension, closed for modification
Disadvantages
- Performance Issues: The interpreter pattern is usually inefficient, especially for complex grammars
- Increased complexity: Complex grammars produce large numbers of classes, increasing system complexity
- Difficult to debug: Debugging complex expression trees can be difficult
Best practices and notes
When to Use
- When the grammar is relatively simple and stable
- When execution efficiency is not the primary consideration
- When new grammar rules need to be added frequently
Alternatives
For complex grammars, consider the following alternatives:
- Use an existing parser generator(such as ANTLR, PLY)
- Use a compiler/interpreter framework
- Consider other design patterns, such as the visitor pattern to handle abstract syntax trees
Performance optimization tips
Example
class
OptimizedExpression
(
Expression
)
:
"""Optimized expression base class"""
def
init
(
self
)
:
self
._cache
=
{
}
Add a caching mechanism
def
interpret
(
self
,
context
)
:
Use caching to avoid repeated computation
cache_key
=
id
(
context
)
if
cache_key
not
in
self
._cache:
self
._cache
[
cache_key
]
=
self
._do_interpret
(
context
)
return
self
._cache
[
cache_key
]
def
_do_interpret
(
self
,
context
)
:
"""Actual interpret logic, implemented by subclasses"""
pass
Practical Exercise
Exercise 1: Extend the Calculator
Add the following features to the calculator:
- Division operation
- Modulo operation
- Support parenthesis precedence
Exercise 2: Implement a Boolean Expression Interpreter
Create a Boolean expression interpreter that supports:
- AND, OR, NOT operations
- Comparison operations (>, <, >=, <=, ==, !=)
- Variable substitution
Exercise 3: Design a Rule Engine
Use the interpreter pattern to design a simple rule engine that can:
- Parse business rules
- Evaluate rules based on input data
- Output decision results
Summary
The interpreter pattern provides an elegant solution for handling domain-specific languages (DSLs). Although in real projects we prefer to use professional parsing tools for complex grammars, understanding the principles of the interpreter pattern is important for mastering compiler theory and language processing.
Remember the core idea of design patterns:Not every pattern suits every scenario; choosing the solution best suited to current needs is the key.