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

Larry Bates lbates at swamisoft.com
Wed Jul 21 15:56:28 EDT 2004


>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']

>>>print f()

12

"tedsuzman" <tedsuzman at yahoo.com> wrote in message
news:mailman.672.1090438155.5135.python-list at python.org...

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