pyppin.util.expression

[View Source]

Safe evaluation of Python expressions.

Classes

Expression(expression, *[, functions, ...])

Expression implements "safe" evaluation of user-entered Python expressions.

class pyppin.util.expression.Expression(expression: str, *, functions: List[Callable] = [], allow_attribute_functions: bool = False, variables: Optional[List[str]] = None)[source]

Bases: object

Expression implements “safe” evaluation of user-entered Python expressions.

This is safe in that it tries to ensure that the given expression cannot mutate the state of the system (e.g. modifying attributes), execute I/O, or change the broader control flow. However, it is not perfectly safe: Sufficiently complex expressions can crash the entire interpreter! See compile() for details. Length-limiting the input may help.

Parameters
  • expression – A Python expression to be turned into this object.

  • functions – A list of functions which may be used in expressions. By default, only the “safe” builtin functions (see SAFE_BUILTINS, below) are permitted; any others must be explicitly specified.

  • allow_attribute_functions – By default, while all attributes of variables passed in to the expression may be referenced, if the variable contains a function (e.g., x.foo()) then that function may not be called. If this is set to true, such functions are permitted. This default makes it safe to pass objects which have potentially dangerous methods for their data alone. Note that variable properties are always accessible.

  • variables – If given, a list of variable names which may be referenced by the expression. In this case, any reference to variables not in this list will raise a SyntaxError at construction time. If not given, all variable names are permitted, and the actual set of variables used can be checked with the variables property of this object.

Raises
  • SyntaxError – If the expression cannot be parsed, or if the expression attempted to do something forbidden, like reference an unknown variable.

  • ValueError – If the expression string contains NUL bytes for some reason.

property variables: Tuple[str, ...][source]

List all variables and functions referenced by this expression.

property free_variables: Tuple[str, ...][source]

List all the “free” variables, i.e. the ones that must be specified by arguments when calling the function.

property ast: AST[source]

The AST representation of this function.

functions() Dict[str, Callable][source]

The dictionary of available functions callable by this function.

is_valid_function(name: str) bool[source]

Test if the given name is a valid function for use in this expression.

This is faster than checking if name is in self.functions().