Python handles globals badly.

Chris Angelico rosuav at gmail.com
Fri Sep 11 11:55:28 EDT 2015


On Sat, Sep 12, 2015 at 1:49 AM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
>> And that's the thing... I think. It's using locals(), which starts out
>> as a copy of the function's locals (in this example, empty), but
>> without assignment affecting anything. Which is more than a little
>> weird:
>>
>>>>> def f():
>> ...     x = [1]
>> ...     exec("print(x); x[0] = 2; print(x); x = [3]; print(x)")
>> ...     print(x)
>> ...
>>>>> f()
>> [1]
>> [2]
>> [3]
>> [2]
>
> Ah, that makes sense. It's writing into the dict that is created and
> returned by locals(), but not actually updating the frame locals which
> are the source of truth.

Yeah... but it only makes sense to people who understand the
implementation. It's certainly not a logical and sane behaviour that
would be worth documenting and using.

ChrisA



More information about the Python-list mailing list