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

tedsuzman tedsuzman at yahoo.com
Wed Jul 21 15:29:12 EDT 2004


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

print f()
-----

The above prints '12', as expected. However,

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

print f()
------

prints '2'. 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() consist of the current
scope? Why aren't the two examples above equivalent?




More information about the Python-list mailing list