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

Benjamin Peterson benjamin at python.org
Fri May 3 04:43:09 CEST 2013


2013/5/2 Nick Coghlan <ncoghlan at gmail.com>:
> 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.
>
> Rather than adding this low level detail to the library reference
> docs, I would suggest adding it to the data model section of the
> language reference, with a link to the appropriate section from the
> docs for the locals() builtin. The warning in the locals() docs would
> be softened to indicate that modifications won't work at function
> scope, but are supported at module and class scope.

This sounds good to me.

--
Regards,
Benjamin


More information about the Python-Dev mailing list