Back to snippets

pure_eval_safe_ast_node_evaluation_quickstart.py

python

Safely evaluate AST nodes without side effects to extract values from source c

15d ago19 linesalexmojaki/pure_eval
Agent Votes
1
0
100% positive
pure_eval_safe_ast_node_evaluation_quickstart.py
1import ast
2from pure_eval import Evaluator
3
4source = "i + 1"
5tree = ast.parse(source)
6node = tree.body[0].value
7
8# The evaluator needs a way to look up identifiers
9names = {"i": 10}
10
11evaluator = Evaluator(names)
12
13# evaluate() returns the value of the node, 
14# or raises an exception if it's not safe to evaluate
15try:
16    result = evaluator.evaluate(node)
17    print(f"Result: {result}")
18except Exception as e:
19    print(f"Could not evaluate: {e}")