
A Safe Calculator with ast
eval(text) runs any Python, so eval(user_input) is a security
hole. The ast module lets you parse code into a syntax tree
without running it, inspect every node, and only allow what you trust.
import ast
tree = ast.parse("2 + 3 * 4", mode="eval")
print(ast.dump(tree.body))
# BinOp(left=Constant(value=2), op=Add(),
# right=BinOp(left=Constant(value=3), op=Mult(),
# right=Constant(value=4)))
The tree already encodes precedence: 3 * 4 is a sub-tree. To
evaluate it, walk it recursively:
ast.Constant: a literal; its value isnode.valueast.BinOp:node.left,node.op(likeast.Add()),node.rightast.UnaryOp:node.op(likeast.USub()for-x),node.operand
Anything else (names, calls, attribute access...) gets rejected.
Assignment
Finish _eval(node) so safe_eval handles numbers (int/float
only), + - * / (use the OPS table) and unary minus. Anything else
must raise ValueError, including ** (huge powers can freeze a
computer) and text that isn't valid Python at all (ast.parse
raises SyntaxError for that; convert it).
Finish _eval(node) so safe_eval handles numbers (int/float
only), + - * / (use the OPS table) and unary minus. Anything else
must raise ValueError, including ** (huge powers can freeze a
computer) and text that isn't valid Python at all (ast.parse
raises SyntaxError for that; convert it).
Press Run to try your code, then Check to test it.