Registry / testing / pure-eval

pure-eval

JSON →
library0.2.3pypypi✓ verified 27d ago

pure-eval is a Python library (current version 0.2.3) designed to safely evaluate Abstract Syntax Tree (AST) nodes without allowing arbitrary code execution or unwanted side effects. It provides a controlled way to inspect and compute values from Python expressions, making it suitable for static analysis and secure evaluation contexts. The library is actively maintained, with updates released periodically.

pip install pure-eval
INSTALL
IMPORT
SIG · PURE-EVAL
P
pure-eval
testingpythonv0.2.3
Install
1.6s avg
Import
27ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.2.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.028s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.026s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Evaluator
from pure_eval import Evaluator
CannotEval
from pure_eval import CannotEval

This example demonstrates how to use `pure-eval` to safely evaluate an AST node representing a pure mathematical expression. It also shows how the library prevents evaluation of expressions that might cause side effects, such as accessing a property that modifies internal state, by raising a `CannotEval` exception. For security, `__builtins__` are explicitly disabled in the evaluator context.

import ast from pure_eval import Evaluator, CannotEval class Rectangle: def __init__(self, width, height): self.width = width self.height = height self.area_computed = False @property def area(self): self.area_computed = True # This is a side effect return self.width * self.height # Create an AST node representing a pure expression rect_node = ast.parse("rect.width * rect.height").body[0].value rect_instance = Rectangle(10, 5) # Initialize Evaluator with the context. Disable builtins for security. evaluator = Evaluator({ "rect": rect_instance, "__builtins__": {} }) try: result = evaluator.evaluate(rect_node) print(f"Evaluated pure result: {result}") except CannotEval as e: print(f"Could not evaluate pure expression: {e}") # Create an AST node representing an expression with a potential side effect side_effect_node = ast.parse("rect.area").body[0].value try: evaluator.evaluate(side_effect_node) except CannotEval as e: print(f"Refused to evaluate expression with potential side effect: {e}") # Verify no side effect occurred from the attempted evaluation print(f"Area computed flag: {rect_instance.area_computed}")
Debug
Known issues
gotchapure-eval is explicitly designed to raise a `CannotEval` exception when it encounters expressions that could have side effects, such as calling functions, accessing properties with getters that modify state, or modifying variables. It is not a drop-in replacement for Python's built-in `eval()` function for arbitrary code.
fix
Ensure that the AST nodes you intend to evaluate represent genuinely pure expressions. Anticipate and handle `CannotEval` exceptions for any expressions that might involve non-pure operations.
affects: All versions
gotchaBy default, `pure-eval`'s `Evaluator` might inherit built-in functions and names from the execution environment. For maximum security and a truly 'pure' evaluation context, explicitly pass an empty dictionary `{}` or a carefully curated whitelist of safe built-ins to the `__builtins__` key in the `global_context` dictionary when initializing `Evaluator`.
fix
Initialize `Evaluator` with `Evaluator(global_context={'__builtins__': {}})` or a custom safe dictionary for `__builtins__`.
affects: All versions
gotchaThe `Evaluator` class in `pure-eval` does not have an `evaluate` method. The primary method for evaluating AST nodes is `eval` (or `exec`). Attempting to call `evaluator.evaluate()` will result in an `AttributeError`.
fix
Ensure you are using the correct method for evaluation, typically `evaluator.eval(ast_node)`.
affects: All versions
gotchaThe `Evaluator` class in `pure-eval` does not expose a method named `evaluate`. Attempting to call `evaluator.evaluate(...)` will result in an `AttributeError`.
fix
Instead of `evaluator.evaluate(node)`, use `evaluator.eval_ast(node)` to evaluate an AST node, or `evaluator.eval_expr(expression_string)` to evaluate a Python expression string. Consult the `pure-eval` library's documentation for the correct method signature and usage based on your input type.
affects: All versions
Errors
Common errors & fixes
CannotEval
The `pure-eval` library raised this exception because it encountered an AST node or operation that it deems unsafe or cannot evaluate according to its strict safety rules, such as attempting to execute arbitrary code or access forbidden attributes.
fix
Review the AST node being evaluated and ensure it consists only of safe expressions and operations that `pure-eval` is designed to handle. Avoid attempting to evaluate statements (like `import`, `def`, `class`) or expressions that access potentially unsafe attributes or functions.
ModuleNotFoundError: No module named 'pure_eval'
The `pure-eval` library is not installed in the current Python environment, or the Python interpreter cannot find it.
fix
Install the library using pip: `pip install pure-eval` or ensure your virtual environment is activated and the dependency is correctly listed and installed.
SyntaxError: invalid syntax
This typically occurs when trying to use Python's built-in `eval()` function (not `pure-eval`) with a string that contains a statement (e.g., `import`, `def`, `class`) instead of a pure expression. `eval()` can only evaluate expressions, not statements.
fix
If you are trying to evaluate expressions, ensure the input string to `eval()` or the AST node passed to `pure-eval`'s evaluator is a valid expression. If you intend to execute statements, consider using `exec()` (with extreme caution due to security risks) or parse the code into an AST and process it using `pure-eval`'s capabilities, understanding that `pure-eval` will likely raise `CannotEval` for inherently unsafe statement nodes.
Upgrade
Version history
0.2.3latest on PyPI · released Jul 21, 2024
Audit
Dependencies

No dependency data recorded yet.

Agent activity
14 hits · last 30 days
node
13
Resources
pure-eval — pip install pure-eval · libregistry