[Python-Dev] PEP 558: Defined semantics for locals()

Nick Coghlan ncoghlan at gmail.com
Tue May 28 11:15:32 EDT 2019


On Sun, 26 May 2019 at 00:37, Guido van Rossum <guido at python.org> wrote:
>
> This looks great.
>
> I only have two nits with the text.
>
> First, why is the snapshot called a "dynamic snapshot"? What exactly is dynamic about it?

The dynamic part comes in if you call locals() twice: because it
returns the same mapping object every time, the second call to
locals() will update the snapshot with the updated values of the local
variables. To get a static snapshot that won't be implicitly updated
by subsequent calls to locals() (or accesses to frame.f_locals, or
implicit updates prior to trace function invocation) you have to do
"locals().copy()".

As others have noted, this isn't the behaviour we would choose if we
were designing this API from scratch, but the current CPython
behaviour has ~18 years of de facto standardisation behind it (as near
as I can tell it has worked this way since nested scopes and fast
locals were introduced in Python 2.1), so I'd be pretty hesitant about
changing it at this point.

In particular, I want to preserve the existing behaviour of Python 3
code that runs exec() and eval() at function scope, which means
ensuring that locals():

1. Continues to behave like a normal dict instance when passed to another API
2. Continues to leave the actual local variables of the calling frame alone

> Second, you use the word "mapping" a lot. Would you mind changing that to "mapping object" in most places? Especially in the phrase "each call to ``locals()`` returns the *same* mapping". To me, without the word "object" added, this *could* be interpreted as "a dict with the same key/value pairs" (since "mapping" is also an abstract mathematical concept describing anything that maps keys to values).

That makes sense - I'll update the text.

Cheers,
Nick.

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


More information about the Python-Dev mailing list