Questions about `locals` builtin

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Feb 26 19:25:53 EST 2018


On Mon, 26 Feb 2018 21:55:35 +0300, Kirill Balunov wrote:

> Hi,
> 
> I am a little bit confused with `locals` builtin in these moments:
> 
> 1. The documentation says that _free varaibles_ are returned, which
> seems incorrect description.

I can't answer that, sorry.


> 2. The documentation has a note that "The contents of this dictionary
> should not be modified". Which implies that it is a read only mapping.
> So the question why it is `dict` instead of `types.MappingProxyType`?

Mostly because locals() predates MappingProxyType by many years, and also 
because that restriction doesn't apply to other implementations of Python 
such as Jython and IronPython.

In CPython, the dict returned by locals() is a copy of the local 
namespace, so modifying the dict doesn't modify the real local variables.

(Well, sometimes it does, but not always. The story in Python 2 is really 
complex.)

But in Jython and IronPython, it actually is the namespace, so writing to 
it works like writing to globals.

So writing to locals *sometimes* works, and cannot be prohibited 
outright, but if you want portable code, you have to avoid it.


> 3. There is one more moment: local variables had been determined when
> function was compiled. But `locals` returns _some_ current runtime copy.

Have you tried it in Python 2 or 3? The behaviour may be less confusing 
in 3.



-- 
Steve




More information about the Python-list mailing list