Safe Python Expression Evaluator
asteval provides a safe, minimalistic, and flexible Python expression evaluator built on the Abstract Syntax Tree (AST) module. It is designed to evaluate untrusted code within a sandboxed environment, offering fine-grained control over available symbols and operations. The current version is 1.0.8, with a development cadence focused on security enhancements, bug fixes, and supporting newer Python versions.
Warnings
- breaking For enhanced security, `asteval` (starting from v1.0.1 and further hardened in v1.0.6 and v1.0.8) explicitly disallows or removes by default access to several potentially unsafe functions or modules. This includes `string.format()`, `numpy.memmap`, `numpy.linalg`, `numpy.polynomial`, and `numpy.fft`. Attempts to use these will raise errors unless they are explicitly and carefully re-enabled.
- gotcha Lambda expressions (`lambda`) were not fully supported in `asteval` until version 1.0.8. Code relying on `lambda` will fail to parse or execute correctly on earlier `asteval` versions.
- gotcha The behavior of `return` statements within `while`, `for`, or `with` blocks inside `asteval` functions (referred to as 'Procedures') was inconsistent in versions prior to 1.0.7. This could lead to `return` statements not correctly exiting the function as expected, potentially resulting in unexpected code execution.
- breaking `asteval` has progressively dropped support for older Python versions. As of version 1.0.7, Python 3.9 is no longer supported, and version 1.0.6 dropped support for Python 3.8. The current minimum required Python version is 3.10.
Install
-
pip install asteval
Imports
- Interpreter
from asteval import Interpreter
Quickstart
from asteval import Interpreter
aeval = Interpreter()
# Define variables and execute expressions
aeval("x = 1 + 2")
aeval("y = x * 3")
# Access results from the symbol table
result = aeval.symtable['y']
print(f"Result: {result}")
# Evaluate a direct expression
direct_result = aeval.eval("10 * x + y")
print(f"Direct evaluation: {direct_result}")