evaluate.py 1007 B

1234567891011121314151617181920212223242526272829303132333435
  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. elif isinstance(node, ast.Name):
  16. return names[node.id]
  17. elif isinstance(node, ast.UnaryOp):
  18. operand = _evaluate(node.operand, names=names)
  19. return _OPERATORS[type(node.op)](operand)
  20. elif 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. else:
  25. raise Exception(node)
  26. def evaluate_expression(expr_str, names):
  27. expr = ast.parse(expr_str, mode="eval")
  28. return _evaluate(expr.body, names=names)