Question about name scope

Ethan Furman ethan at stoneleaf.us
Wed Feb 1 18:08:24 EST 2012


Ethan Furman wrote:
> Ian Kelly wrote:
>> I am not a dev, but I believe it works because assigning to locals()
>> and assigning via exec are not the same thing.  The problem with
>> assigning to locals() is that you're fundamentally just setting a
>> value in a dictionary, and even though it happens to be the locals
>> dict for the stack frame, Python can't figure out that it should go
>> and update the value of the optimized local to match.  exec, on the
>> other hand, compiles and executes an actual STORE_NAME operation.  Of
>> course, if the particular local variable hasn't been optimized by the
>> compiler, then updating locals() works just fine (although you
>> probably should not rely on this):
>>
>>>>> def f(x, y):
>> ...     locals()[x] = y
>> ...     print locals()[x]
>> ...     exec 'print ' + x
>> ...
>>>>> f('a', 42)
>> 42
>> 42
> 
> Definitely should rely on it, because in CPython 3 exec does not 
> un-optimize the function and assigning to locals() will not actually 
> change the functions variables.


Ouch, that should have been *not* rely on it; not because it doesn't 
work (exec uses locals() if one is not specified), but because it is 
easy for the names in the function to get out of sync with the names in 
the functions locals() (or __dict__).

~Ethan~



More information about the Python-list mailing list