Nested Scopes Question (exec)

Tim Peters tim.one at home.com
Sun Jun 24 19:26:36 EDT 2001


[Ryan LeCompte]
> ...
> The PEP states that the SyntaxError exception will be raised for "bare
> execs" which don't utilize the full syntax as given above, but why does
> the exception disappear when the full syntax is used?  How does the
> compiler know that the exec statement won't introduce a new local
> variable in the local namespace,

It can't introduce a new local variable, although you may have code that
makes you believe that it does <wink>.  Read on.

> ...
> P.S. --- Aren't the following two calls the same:
>
> exec "print 'hello'"
> exec "print 'hello'" in globals(), locals()

Those are the same, but neither one has well-defined behavior.  Python
should really gripe about the second version too, but it can't know at
compile-time that "locals()" refers to the builtin function of that name, so
it could at best be a warning.  As the docs for locals() say,

    Warning:  The contents of this dictionary should not be modified;
    changes may not affect the values of local variables used by the
    interpreter.

That is, attempting to modify locals() has no defined behavior, so anything
you see as a result of modifying locals() is use-at-your-own-risk stuff.
The exact rules for when modifying locals() will and won't have an effect on
the local namespace vary from release to release, and across
implementations, and are all accidents.  If Python ever grows an immutable
dict type, it's a safe bet that locals() will return an instance of that
type, so that attempts to mutate it will raise exceptions.

I wouldn't be surpised if the "bare exec" syntax form got deprecated too
(Guido has already said that he intends to ban it someday).

In the meantime, best practice is:

1. Never use locals() in a mutating context.

2. Pass explicit dicts to exec (and related functions), amd not
   including locals() unless you're certain the exec'ed code won't
   mutate it.

3. globals() is safe to use (has guaranteed behavior) in all contexts.





More information about the Python-list mailing list