pythoneval

In python, how do I evaluate a statement from a string and get the value if it's an expression?


In python, I would like to take one statement (as a string) and execute it. If the statement is an expression, I'd like to get the value of the expression.

eval() doesn't handle statements, only expressions. exec() handles statements but doesn't give a way to retrieve a value if the statement is an expression.

It seems that eval(compile(x, '<string>', 'single')) is almost what I need, but it prints a non-None return value instead of returning it.

Is there a way to do this?


Solution

  • Use try/except to handle both cases.

    try:
        result = eval(input_string)
        # do something with result
    except SyntaxError:
        exec(input_string)