|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import ast, math |
| 4 | + |
| 5 | + |
| 6 | +class MathEvaluator: |
| 7 | + """ Evaluate math expressions |
| 8 | + |
| 9 | + ..code::py |
| 10 | + # Example usage |
| 11 | + mev = MathEvaluator() |
| 12 | + print(mev.evaluate("e-1+cos(2*pi)")) |
| 13 | + print(mev.evaluate("pow(2, 8)")) |
| 14 | + print(mev.evaluate("round(sin(pi), 3)")) |
| 15 | + """ |
| 16 | + |
| 17 | + # Allowed math symbols |
| 18 | + allowed_symbols = { |
| 19 | + "e": math.e, "pi": math.pi, |
| 20 | + "cos": math.cos, "sin": math.sin, "tan": math.tan, "exp": math.exp, |
| 21 | + "pow": pow, "round": round, "abs": abs, "min": min, "max": max, |
| 22 | + "sqrt": math.sqrt, "log": math.log |
| 23 | + } |
| 24 | + |
| 25 | + # Allowed AST node types |
| 26 | + allowed_nodes = ( |
| 27 | + ast.Expression, ast.BinOp, ast.UnaryOp, ast.Call, ast.Name, ast.Load, |
| 28 | + ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.Mod, ast.FloorDiv, |
| 29 | + ast.USub, ast.UAdd, ast.BitXor, ast.BitOr, ast.BitAnd, |
| 30 | + ast.LShift, ast.RShift, ast.Invert, |
| 31 | + ast.Constant |
| 32 | + ) |
| 33 | + |
| 34 | + def _validate_ast(self, node): |
| 35 | + for child in ast.walk(node): |
| 36 | + if not isinstance(child, self.allowed_nodes): |
| 37 | + raise ValueError(f"Bad expression: {ast.dump(child)}") |
| 38 | + # Check that all variable/function names are whitelisted |
| 39 | + if isinstance(child, ast.Name): |
| 40 | + if child.id not in self.allowed_symbols: |
| 41 | + raise ValueError(f"Unknown symbol: {child.id}") |
| 42 | + |
| 43 | + def evaluate(self, expr: str): |
| 44 | + if any(bad in expr for bad in ('\n', '#')): |
| 45 | + raise ValueError(f"Invalid expression: {expr}") |
| 46 | + try: |
| 47 | + node = ast.parse(expr.strip(), mode="eval") |
| 48 | + self._validate_ast(node) |
| 49 | + return eval(compile(node, "<expr>", "eval"), {"__builtins__": {}}, self.allowed_symbols) |
| 50 | + except Exception: |
| 51 | + raise ValueError(f"Invalid expression: {expr}") |
0 commit comments