Lazo Lab Sign up

App 5: Desktop App with Windows & Buttons / Build a calculator

Lesson 5 of 10

Calculating safely

eval() runs any Python code a user types, which is dangerous. Instead, parse the expression yourself or use a small safe evaluator built on the ast module that only allows numbers and + - * /.

Key points

  • Never eval() user input
  • ast.parse reads maths without running code
  • Only allow the operators you expect
import ast, operator
OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv}

def safe_eval(text):
    def walk(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            return OPS[type(node.op)](walk(node.left), walk(node.right))
        raise ValueError("not allowed")
    return walk(ast.parse(text, mode="eval").body)

Your turn

Add safe_eval() and a calculate() that shows the result, or 'Error' if the input is bad.

Watch a video on thisOpens YouTube search results for “Calculating safely” in a new tab

Quiz · +10 XP

Why avoid eval() on user input?

Log in to save progress and earn XP.