pure_eval
This is a Python package that lets you safely evaluate certain AST nodes without triggering arbitrary code that may have unwanted side effects.
It can be installed from PyPI:
pip install pure_eval
To demonstrate usage, suppose we have an object defined as follows:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
print("Calculating area...")
return self.width * self.height
rect = Rectangle(3, 5)
Given the rect object, we want to evaluate whatever expressions we can in this source code:
source = "(rect.width, rect.height, rect.area)"
This library works with the AST, so let's parse the source code and peek inside:
import ast
tree = ast.parse(source)
the_tuple = tree.body[0].value
for node in the_tuple.elts:
print(ast.dump(node))
Output:
Attribute(value=Name(id=rect , ctx=Load()), attr=width , ctx=Load())
Attribute(value=Name(id=rect , ctx=Load()), at
|