[Python-Dev] Should vars() return modifiable dict?

Nick Coghlan ncoghlan at gmail.com
Fri Oct 5 14:58:38 CEST 2012


On Fri, Oct 5, 2012 at 5:29 PM, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
> On Wed, Oct 3, 2012 at 11:34 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> I find myself unable to choose between 2) and 4), which suggests that
>> the status quo wins and we keep the current behaviour.
>
> What is the benefit of having a dict that represents a namespace, but
> whose mutations don't mutate said namespace? Compare with option 2,
> where the dict is mutable, and whose mutations mutate the namespace it
> represents. That behavior is altogether significantly less surprising.
>
> I've never understood why locals() returned a mutable dictionary
> either, except that Python has no immutable dictionary type.

There's no benefit, it's just a historical artefact imposed by
backwards compatibility constraints. We should have taken the
opportunity to fix it in Python 3.0 (just as we dropped support for
"from x import *" at function scope) but I don't believe anyone
suggested it at the time.

The problem is that, while updating it to return
types.MappingProxyType instead would produce more obvious error
messages for those that don't know you can't use it to update local
variables inside a function (even though it works at module and class
scopes), such a change would *break* existing code which knows the
dictionary doesn't get written back, and just uses it for its own
purposes (e.g passing it to exec).

As for *why* changes don't get written back, it's because the compiler
is allowed to assume it knows about every variable name that exists in
the local scope (by design), and that doesn't fit with writable
locals() for functions.

Cheers,
Nick.

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


More information about the Python-Dev mailing list