exec and globals and locals ...
Eko palypse
ekopalypse at gmail.com
Wed Sep 18 17:47:09 EDT 2019
Why does f1 work? I've expected an exception as no global dict has been provided, and why does throw f3 an exception if it does, more or less, the same as f1?
x += 5
def f1():
exec("x += 1; print('f1 in:', x)")
return x
print('f1 out', f1())
# result => f1 in: 6
# result => f1 out 5
x = 5
def f2():
exec("x += 1; print('f2 in:', x)", globals())
return x
print('f2 out', f2())
# result => f2 in: 6
# result => f2 out 6
exec('import test01', globals())
print('f3 out', x)
# result exception, expected but because f1 didn't throw an exception
# I'm confused. module test01 has only this two lines
x += 1
print('f3 in:', x)
Thank you
Eren
More information about the Python-list
mailing list