_evaluate.py 951 B

1234567891011121314151617181920212223242526272829303132
  1. import ast
  2. import operator as python_operator
  3. _OPERATORS = {
  4. ast.Add: python_operator.add,
  5. ast.Div: python_operator.truediv,
  6. ast.Mult: python_operator.mul,
  7. ast.Pow: python_operator.pow,
  8. ast.Sub: python_operator.sub,
  9. ast.USub: python_operator.neg,
  10. }
  11. def _evaluate(node, names):
  12. if isinstance(node, ast.Num):
  13. return node.n
  14. if isinstance(node, ast.Name):
  15. return names[node.id]
  16. if isinstance(node, ast.UnaryOp):
  17. operand = _evaluate(node.operand, names=names)
  18. return _OPERATORS[type(node.op)](operand)
  19. if isinstance(node, ast.BinOp):
  20. operand_left = _evaluate(node.left, names=names)
  21. operand_right = _evaluate(node.right, names=names)
  22. return _OPERATORS[type(node.op)](operand_left, operand_right)
  23. raise ValueError(node)
  24. def evaluate_expression(expr_str, names):
  25. expr = ast.parse(expr_str, mode="eval")
  26. return _evaluate(expr.body, names=names)