SimpleEval
SimpleEval is a Python library designed for safely evaluating simple expressions provided by untrusted users. It acts as a controlled alternative to Python's built-in `eval()` function, parsing expressions using the `ast` module to restrict executable operations, functions, and names. This prevents malicious code execution while allowing flexible, user-defined calculations. The current version is 1.0.7, and the library maintains an active development and release cadence.
Warnings
- breaking SimpleEval 1.0.0 and later versions dropped support for Python versions prior to 3.9. If you need to support older Python environments, you must use an older version of SimpleEval.
- breaking A critical vulnerability (CVE-2026-32640) allows objects passed into SimpleEval to potentially leak dangerous modules (like `os` or `sys`) through attributes or callbacks, leading to sandbox escapes. This could allow an attacker to execute arbitrary code.
- gotcha The default configuration of SimpleEval limits the `**` (power) operator to prevent Denial-of-Service (DoS) attacks from extremely large calculations. Similarly, string and comprehension lengths are capped.
- gotcha In Python, the `^` operator performs a bitwise XOR, not exponentiation. Users expecting `3 ^ 2` to yield 9 (like in some other languages) will get 1 (3 XOR 2).
- gotcha By default, SimpleEval restricts access to object attributes (especially those starting with `_` or `func_`) and disallows sensitive built-in functions (e.g., `type`, `open`). Module access is also highly restricted.
Install
-
pip install simpleeval
Imports
- simple_eval
from simpleeval import simple_eval
- SimpleEval
from simpleeval import SimpleEval
- BASIC_ALLOWED_ATTRS
from simpleeval import BASIC_ALLOWED_ATTRS
- EvalWithCompoundTypes
from simpleeval import EvalWithCompoundTypes
Quickstart
from simpleeval import simple_eval, SimpleEval
# Basic evaluation
result1 = simple_eval("21 + 21")
print(f"Basic evaluation: {result1}") # Expected: 42
# Evaluation with custom names and functions
s = SimpleEval(names={'x': 10, 'y': 5}, functions={'add_one': lambda val: val + 1})
result2 = s.eval("x * y + add_one(2)")
print(f"Custom evaluation: {result2}") # Expected: 52 (10 * 5 + 3)
# Allowing safe attribute access
from simpleeval import BASIC_ALLOWED_ATTRS
s_attrs = SimpleEval(names={'my_string': ' hello '}, allowed_attrs=BASIC_ALLOWED_ATTRS)
result3 = s_attrs.eval("my_string.strip().upper()")
print(f"Attribute access: {result3}") # Expected: ' HELLO '