+ 2

What's the difference between exec() and eval()

i saw that eval(print(''asd'')) and exec(print(''asd'')) do the same thing but i think that there are some differences

12th May 2018, 3:39 PM
Etabeta1🇼đŸ‡č
Etabeta1🇼đŸ‡č - avatar
2 Answers
+ 5
Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects. eval and exec have these two differences: eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on. An expression in Python is whatever you can have as the value in a variable assignment: eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything). The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression
12th May 2018, 4:27 PM
Maninder $ingh
Maninder $ingh - avatar
0
thx
12th May 2018, 6:48 PM
Etabeta1🇼đŸ‡č
Etabeta1🇼đŸ‡č - avatar