git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


On 5/27/19 9:12 AM, Terry Reedy wrote:
> On 5/27/2019 3:18 AM, Greg Ewing wrote:
>> Chris Angelico wrote:
>>> Except that it does. After calling locals() a second time, the result
>>> of the *first* call will be updated to reflect changes.
>>
>> Yeow. That's *really* unintuitive. There had better be an extremely
>> good reason for this behaviour.
>
> I believe that the situation is or can be thought of as this: there is
> exactly 1 function locals dict.? Initially, it is empty and
> inaccessible (unusable) from code.? Each locals() call updates the
> dict to a current snapshot and returns it.
>
I had a similar concern, and one BIG issue with it being define this way
is that you get a fundamental re-entrancy problem. If module a uses
locals(), and then calls module b that uses locals(), module a has lost
its usage. One implication of this is that then you really want ALL
modules to define if they use the locals() function or not, then you get
the question, does this 1 of apply across threads? does a call to locals
in another thread make me lose my locals (or does each thread get its
own version), if that is true then if you might possible be in a
situation where threads are in play you MUST make the copy anyway, and
do it fast enough that the GIL isn't released between the snapshot and
the copy (if possible),

C made this sort of mistake decades ago for some functions, not thinking
about threads or re-entrancy, and had to create solutions to fix it. Let
us not forget history and thus repeat it.

Is there a fundamental reason that local needs to keep a single dict, as
opposed to creating a new one for each call? The way it is currently
defined, once it is called, the snapshot will stay forever, consuming
resources, while if a new dict was created, the resource would be
reclaimed after use. Yes, if called twice you end up with two copies
instead of both being updated to the current, but if you WANTED to just
update the current copy, you could just rebind it to the new version,
otherwise you are just forcing the programmer to be making the copies
explicitly.

-- 
Richard Damon