Question about name scope

Ethan Furman ethan at stoneleaf.us
Wed Feb 1 23:24:28 CET 2012


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.

~Ethan~



More information about the Python-list mailing list