Python Language Incompatibilities moving from Python 2 to Python 3 exec statement is a function in Python 3

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


In Python 2, exec is a statement, with special syntax: exec code [in globals[, locals]]. In Python 3 exec is now a function: exec(code, [, globals[, locals]]), and the Python 2 syntax will raise a SyntaxError.

As print was changed from statement into a function, a __future__ import was also added. However, there is no from __future__ import exec_function, as it is not needed: the exec statement in Python 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. Thus you can change the statements

Python 2.x2.3
exec 'code'
exec 'code' in global_vars
exec 'code' in global_vars, local_vars

to forms

Python 3.x3.0
exec('code', global_vars)
exec('code', global_vars, local_vars)

and the latter forms are guaranteed to work identically in both Python 2 and Python 3.

Got any Python Language Question?