r/learnpython • • 9d ago

can i make the exec() command only execute if the code is functional and wont return an error?

So i want to make something where you can input() a math problem and get an answer thru the text output, but if there is a syntax error, i want it to just reopen the prompt instead of crashing, is there a way that i can check if the code is valid before executing? thanks!

0 Upvotes

25 comments sorted by

View all comments

12

u/Discordbothost 9d ago

to answer the literal question: yes, you can check the syntax without running anything. ast.parse just reads the text and raises SyntaxError if it isn't valid. and since it gives you the parsed tree, you can also reject anything that isn't plain math, which fixes the delete-your-files problem people mentioned:

import ast

ALLOWED = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
           ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.USub)

def safe_eval(text):
    tree = ast.parse(text, mode="eval")
    for node in ast.walk(tree):
        if not isinstance(node, ALLOWED):
            raise ValueError("only numbers and + - * / ** allowed")
    return eval(compile(tree, "<input>", "eval"))

then your loop catches (SyntaxError, ValueError, ZeroDivisionError) and asks again. 1/0 is valid syntax so that one only shows up when it runs, that's why it's in the list