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-evalVerified import paths — ran on the pinned version, not inferred.
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.
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.
Initialize `Evaluator` with `Evaluator(global_context={'__builtins__': {}})` or a custom safe dictionary for `__builtins__`.Ensure you are using the correct method for evaluation, typically `evaluator.eval(ast_node)`.
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.
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.
Install the library using pip: `pip install pure-eval` or ensure your virtual environment is activated and the dependency is correctly listed and installed.
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.
No dependency data recorded yet.