SimpleEval

1.0.7 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

Demonstrates basic expression evaluation using `simple_eval` and more advanced usage with the `SimpleEval` class, including custom variables, functions, and safe attribute access.

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 '

view raw JSON →