flare.safeeval
Here we are trying to provide an secure and safe space for evaluate simple python expressions on some ‘data’.
If you only need a oneshot evaluation, you call safeEval and enjoy the result. Otherwise call first compile to get the ast representation and execute that compiled expression multiple times with different data. A plain instance of SafeEval without allowedCallables argument will not accept any method/function like call on execution
Module Contents
Classes
Safely evaluate an expression from an untrusted party. |
- class flare.safeeval.SafeEval(allowedCallables: None | Dict[str, Any] = None)
Safely evaluate an expression from an untrusted party.
- _BoolOp(node, names)
Handling ast.BoolOp in a Pythonic style.
- callNode(node: ast.Call, names: Dict[str, Any]) Any
Evaluates the call if present in allowed callables.
- Parameters:
node – The call node to evaluate
names – a mapping of local objects which is used as ‘locals’ namespace
- Returns:
If allowed to evaluate the node, its result will be returned
- compareNode(node: ast.Compare, names: Dict[str, Any]) bool
Evaluates an ‘if’ expression.
These are a bit tricky as they can have more than two operands (eg. “if 1 < 2 < 3”)
- Parameters:
node – The compare node to evaluate
names – a mapping of local objects which is used as ‘locals’ namespace
- listNode(node, names)
- execute(node: [str, ast.AST], names: Dict[str, Any]) Any
Evaluates the current node with optional data.
- Parameters:
node – The compare node to evaluate
names – a mapping of local objects which is used as ‘locals’ namespace
- Returns:
whatever the expression wants to return
- compile(expr: str) ast.AST
Compiles a python expression string to an ast.
Afterwards you can use execute to run the compiled ast with optional data. If you only want to run a ‘oneshot’ expression feel free to use our safeEval method.
- Parameters:
expr – the expression to compile
- Returns:
the ready to use ast node
- safeEval(expr: str, names: Dict[str, Any]) Any
Safely evaluate an expression.
If you want to evaluate the expression multiple times with different variables use compile to generate the AST once and call execute for each set of variables.
- Parameters:
expr – the string to compile and evaluate
names – a mapping of local objects which is used as ‘locals’ namespace
- Returns:
the result of evaluation of the expression with env provided by names