Example 1 — Compile a Formula Once, Run It Many Times
Compile an expression in eval mode and evaluate it with different values.
expr = compile("x ** 2 + 1", "<formula>", "eval")
print(type(expr).__name__)
for x in [1, 2, 3]:
print(x, eval(expr, {"x": x})) How It Works
- Parsed once. The text is turned into a code object a single time.
- Type, not repr. Printing the type name avoids the address shown in a code object's repr.
- Reused. Each
eval()runs the same compiled code with a newx. - Fixed source. The formula is written by the programmer, never taken from users.

