exec and globals and locals ...

Richard Damon Richard at Damon-Family.org
Thu Sep 19 07:40:44 EDT 2019


On 9/19/19 6:52 AM, Eko palypse wrote:
> Am Donnerstag, 19. September 2019 12:45:35 UTC+2 schrieb Richard Damon:
>> On 9/19/19 6:16 AM, Eko palypse wrote:
>>>> In all cases, if the optional parts are omitted, the code is executed in the current scope. ...
>>>>
>>>>
>>>> You can see from it that "globals" is optional.
>>>> And that, if "globals" is missing, then
>>>> "exec" is executed in the current scope ("f1" in your case).
>>> Thank you for your answer, and that is exactly what confuses me?
>>> Where does x come from? If I only would read x then I would understand why
>>> it can be found/read but I alter it and as such I either have to provide the
>>> info that this is a global variable, declare it inside of f1 or provide 
>>> the globals dict to exec. But I don't do any of it. Why is exec able to use
>>> the global x?
>>>
>>> Eren
>> I think the issue is that x += 1 isn't exactly like x = x + 1, and this
>> is one case that shows it. x = x + 1 is an assignment to the symbol x,
>> which makes x a local, and thus the read becomes an undefined symbol. x
>> += 1 is different, it isn't a plain assignment so doesn't create the
>> local. The read of x is inherently tied to the writing of x so x stays
>> referring to the global.
>>
>> -- 
>> Richard Damon
> Thank you that would never have come to my mind.
> I thought +=1 is just syntactic sugar which clearly isn't.
> If I do the regular x = x + 1 then I do get the expected exception.
>
> Thank you
> Eren

For some objects, += even (possibly) calls a different function __radd__
instead of __add__ (if __radd__ doesn't exist then python will fall back
to using __add__)

This can have a big difference in the case of sharing mutable objects.

x = [1, 2]

y = x

x += [3]

# Now x and y are [1, 2, 3]

x = x + [4]

# Now x = [1, 2, 3, 4] but y is still [1, 2, 3]


-- 
Richard Damon




More information about the Python-list mailing list