evaluate.py 987 B

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