Skip to main content

ducto.expr module

Safe expression evaluator using Python’s ast module.

Allows mathematical expressions with whitelisted variables and functions. Rejects any AST node type not in the allowlist (no eval/exec).

exception ducto.expr.ExpressionError

Bases: Exception

Raised on invalid or unsafe expressions.

ducto.expr.evaluate_expression(expr: str, variables: dict[str, float | int]) → float

Safely evaluate a validated expression.

Args: : expr: Expression string to evaluate. variables: Mapping of variable names to their numeric values.

Returns: : Numeric result of the expression evaluation.

Raises: : ExpressionError: If the expression is invalid or references : unknown variables.

ducto.expr.validate_expression(expr: str) → None

Validate that an expression string is safe and syntactically valid.

Args: : expr: Expression string to validate.

Raises: : ExpressionError: If the expression contains disallowed constructs.