Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables declared in exec'ed code don't become local in Python 3 – documentation?

The code

x = 3
def f():
    exec("x = 2")
    print(x)
f()

runs on both Python 2 and Python 3, but prints different results. Is this change documented anywhere? (A pointer to a mailing list discussion would also be fine -- I ask this purely out of curiosity.)

like image 774
Sven Marnach Avatar asked Oct 05 '11 22:10

Sven Marnach


1 Answers

That's because some hackery were removed from Python 3.

The new documentation about the exec() function has some Notes about that but don't fully explain the situtation.

Python 2, after seeing a exec statement, change every access to vars and functions to LOAD_NAME instead of LOAD_FAST or LOAD_GLOBAL.

Check my other answer about that here.

like image 63
JBernardo Avatar answered Sep 23 '22 20:09

JBernardo