Question about name scope

Ethan Furman ethan at stoneleaf.us
Wed Feb 1 23:53:09 CET 2012


Ian Kelly wrote:
> On Wed, Feb 1, 2012 at 3:24 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> 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.
> 
> Well, the former is not surprising, since exec was changed from a
> statement to a built-in.  I don't see any difference in the way
> locals() behaves, though:
> 
> Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> def f(x, y):
> ...     locals()[x] = y
> ...     print(vars())
> ...     exec('print(' + x + ')')
> ...
>>>> f('a', 42)
> {'y': 42, 'x': 'a', 'a': 42}
> 42
> 
> That still seems to work as I described it.  You couldn't directly
> reference it as 'a', though, since the result would be either that it
> would try to look up a global with that name, or the compiler would
> consider it a local, optimize it, and then you could no longer assign
> it via locals().
> 
> Cheers,
> Ian

--> def f(x, y):
...     locals()[x] = y
...     print(vars())
...     exec('print (' + x + ')')
...     print(x)
...
--> f('a', 42)
{'y': 42, 'x': 'a', 'a': 42}
42
a

Indeed -- the point to keep in mind is that locals() can become out of 
sync with the functions actual variables.  Definitely falls in the camp 
of "if you don't know *exactly* what you are doing, do not play this way!"

~Ethan~



More information about the Python-list mailing list