25 lines
797 B
Python
25 lines
797 B
Python
"""Create constraint lambdas from expressions."""
|
|
|
|
import re
|
|
|
|
|
|
def make_constraint_lambda(expr_str):
|
|
"""Create a lambda function from a constraint expression.
|
|
|
|
Transforms resource identifiers to res dict access and creates a lambda
|
|
with restricted builtins.
|
|
|
|
Args:
|
|
expr_str: Constraint expression like "E[3] >= 50" or "B[2] + S[2] >= 100"
|
|
|
|
Returns:
|
|
A lambda function: lambda res: <evaluated_expression>
|
|
|
|
Raises:
|
|
Exception: If expression fails to eval
|
|
"""
|
|
# Transform identifiers to res subscript access: E -> res["E"], B -> res["B"], etc.
|
|
expr = re.sub(r'\b([A-Z])\b', r'res["\1"]', expr_str)
|
|
|
|
# Create lambda with restricted builtins (no imports, no dangerous functions)
|
|
return eval(f"lambda res: {expr}", {"__builtins__": {}})
|