exec "statement" VS. exec "statement in globals(), locals()

Ted roboteddy at gmail.com
Wed Jul 21 23:56:56 CEST 2004


--------
def f():
	ret = 2
	exec "ret += 10"
	return ret

print f()
--------

The above example prints '12'. However, the following example prints
'2':

--------
def f():
	ret = 2
	exec "ret += 10" in globals(), locals()
	return ret

print f()
--------

According to (http://docs.python.org/ref/exec.html), "In all cases, if
the optional parts are omitted, the code is executed in the current
scope." Don't globals() and locals() comprise the current scope? Why
isn't the output of each example the same?



More information about the Python-list mailing list