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

T

tedsuzman

-----
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?
 
L

Larry Bates

From Python Manual:

execfile(file[, globals[, locals]])
This function is similar to the exec statement, but parses a file instead
of a string. It is different from the import statement in that it does not
use the module administration -- it reads the file unconditionally and does
not create a new module.2.2
The arguments are a file name and two optional dictionaries. The file is
parsed and evaluated as a sequence of Python statements (similarly to a
module) using the globals and locals dictionaries as global and local
namespace. If the locals dictionary is omitted it defaults to the globals
dictionary. If both dictionaries are omitted, the expression is executed in
the environment where execfile() is called. The return value is None.

Warning: The default locals act as described for function locals() below:
modifications to the default locals dictionary should not be attempted. Pass
an explicit locals dictionary if you need to see effects of the code on
locals after function execfile() returns. execfile() cannot be used reliably
to modify a function's locals.

I think the Warning explains it.

You can do:

def f():
l={'ret':2}
exec("ret += 10", globals(), l)
return l['ret']

12
 
M

Michel Claveau, résurectionné d'outre-bombe inform

Hi !


In the syntax 2, because "ret=2", "ret" is local to f()




Try :

chaine="""global ret
ret=ret+10"""

def f():
global ret
ret = 2
exec chaine in globals(), locals() #now, idem exec(chaine)
return ret

print f() #==> 12
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top