[Python-Dev] Tightening up the specification for locals()

Terry Jan Reedy tjreedy at udel.edu
Fri May 3 06:21:44 CEST 2013


On 5/2/2013 9:29 PM, Nick Coghlan wrote:
> An exchange in one of the enum threads prompted me to write down
> something I've occasionally thought about regarding locals(): it is
> currently severely underspecified, and I'd like to make the current
> CPython behaviour part of the language/library specification. (We
> recently found a bug in the interaction between the __prepare__ method
> and lexical closures that was indirectly related to this
> underspecification)
>
> Specifically, rather than the current vague "post-modification of
> locals may not work", I would like to explicitly document the expected
> behaviour at module, class and function scope (as well as clearly
> documenting the connection between modules, classes and the single-
> and dual-namespace variants of exec() and eval()):
>
> * at module scope, as well as when using exec() or eval() with a
> single namespace, locals() must return the same thing as globals(),
> which must be the actual execution namespace. Subsequent execution may
> change the contents of the returned mapping, and changes to the
> returned mapping must change the execution environment.
> * at class scope, as well as when using exec() or eval() with separate
> global and local namespaces, locals() must return the specified local
> namespace (which may be supplied by the metaclass __prepare__ method
> in the case of classes). Subsequent execution may change the contents
> of the returned mapping, and changes to the returned mapping must
> change the execution environment. For classes, this mapping will not
> be used as the actual class namespace underlying the defined class
> (the class creation process will copy the contents to a fresh
> dictionary that is only accessible by going through the class
> machinery).
> * at function scope, locals() must return a *snapshot* of the current
> locals and free variables. Subsequent execution must not change the
> contents of the returned mapping and changes to the returned mapping
> must not change the execution environment.

Except that, apparently, subsequent execution *does* change the returned 
mapping when tracing in on. Some of the loose specification is intentional.

http://bugs.python.org/issue7083
locals() behaviour differs when tracing is in effect

--
Terry Jan Reedy




More information about the Python-Dev mailing list