Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ast
- def limited_eval(node):
- if isinstance(node, ast.Expression):
- return limited_eval(node.body)
- elif isinstance(node, ast.BinOp):
- ops = [
- (ast.Add, lambda a,b: a+b),
- (ast.Sub, lambda a,b: a-b),
- (ast.Mult, lambda a,b: a*b),
- (ast.Div, lambda a,b: a/b)
- ]
- for t, func in ops:
- if isinstance(node.op, t):
- return func(limited_eval(node.left), limited_eval(node.right))
- raise NotImplementedError(f"BinOp with operator {repr(node.op)}")
- elif isinstance(node, ast.Constant):
- return node.value
- else:
- raise NotImplementedError(str(type(node)))
- s = "2+2*3+4/4"
- x = ast.parse(s, mode="eval")
- print(limited_eval(x)) #9.0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement