exec and globals and locals ...
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?
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.