lib5c.util.ast_eval module

Module for safely evaluating arithmetic expressions in strings.

http://stackoverflow.com/a/9558001

lib5c.util.ast_eval.eval_(node, variables)[source]

Inner function for safely evaluating a particular node of an abstract syntax tree. Called recursively to evaluate a string as part of eval_expr().

Parameters:
  • node (ast.AST) – The node of the abstract syntax tree to evaluate.
  • variables (dict) – Dictionary of named variables to use during evaluation.
Returns:

The result of evaluating the node.

Return type:

numeric

lib5c.util.ast_eval.eval_expr(expr, variables=None)[source]

Safely evaluates a simple mathematical expression passed as a string.

Parameters:
  • expr (str) – The expression to evaluate.
  • variables (dict, optional) – Dict mapping variable names to values. These variables can then be used as substrings of expr. Pass None to evaluate the expression without using any named variables.
Returns:

The result of evaluating the expression.

Return type:

numeric

Examples

>>> eval_expr('2^6')
4
>>> eval_expr('2**6')
64
>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
-5.0