I want to execute a correct Python program using exec()
and then get variables and their values after executing. Google says that I should create a dictionary and write the result of execution there: exec(code_object)
in variables. But unfortunately that doesn't in Python 3.
Asked
Active
Viewed 986 times
1
-
possible duplicate of [Behaviour of exec function in Python 2 and Python 3](http://stackoverflow.com/questions/15086040/behaviour-of-exec-function-in-python-2-and-python-3) – Martijn Pieters Jan 12 '15 at 14:19
1 Answers
1
The code in Python 3 should be:
exec(code_object, variables)
This syntax is also Python 2 compatible.
exec(code_object) in variables
would compile and run in Python 3 but do something completely different from Python 2 - it would execute the code_object
in current scope; the exec
would return None
; then the expression None in variables
would evaluate False
since None
is not a key in variables
; the result would be dropped - thus neither compile time nor possibly run-time error occurs, except for code_object
seeing the wrong scope.

Community
- 1
- 1

Antti Haapala -- Слава Україні
- 129,958
- 22
- 279
- 321