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

Nick Coghlan ncoghlan at gmail.com
Sun May 12 15:22:39 CEST 2013

On Sun, May 12, 2013 at 10:01 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Fri, 03 May 2013 12:43:41 +1000
> Steven D'Aprano <steve at pearwood.info> wrote:
>> On 03/05/13 11:29, 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)
>> Fixing the underspecification is good. Enshrining a limitation as the
>> one correct way, not so good.
> I have to say, I agree with Steven here. Mutating locals() is currently
> an implementation detail, and it should IMHO stay that way. Only
> reading a non-mutated locals() should be well-defined.

At global and class scope (and, equivalently, in exec), I strongly
disagree. There, locals() is (or should be) well defined, either as
identical to globals(), as the value returned from __prepare__() (and
will be passed to the metaclass as the namespace). The exec case
corresponds to those two instances, depending on whether the single
namespace or dual namespace version is performed.

What Steven was objecting to was my suggestion that CPython's current
behaviour where mutating locals() may not change the local namespace
be elevated to an actual requirement where mutating locals *must not*
change the local namespace. He felt that was overspecifying a
CPython-specific limitation, and I think he's right - at function
scope, the best we can say is that modifying the result of locals()
may or may not make those changes visible to other code in that
function (or closures that reference the local variables in that


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list