Locals [was Re: unintuitive for-loop behavior]
Chris Angelico
rosuav at gmail.com
Mon Oct 3 00:49:14 EDT 2016
On Mon, Oct 3, 2016 at 3:09 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> But if it did, then just as in the similar situation in IronPython and Jython,
> you would still need to convince the compiler to use LOAD_FAST or equivalent in
> order to see it. Hence:
>
>
> x = y = 'global'
> def example():
> locals()['x'] = 'local'
> locals()['y'] = 'local'
> if False:
> # convince the compiler to treat y as a local
> del y
> print(x) # => 'global' in everything
> print(y) # => 'local' in Jython/IronPython, UnboundLocalError in CPython
Or convince it to use LOAD_NAME. They're Python 2 implementations,
right? Here's CPython at work...
Python 2.7.12+ (default, Sep 1 2016, 20:27:38)
[GCC 6.2.0 20160822] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = y = 'global'
>>> def example():
... locals()['x'] = 'local'
... locals()['y'] = 'local'
... if False:
... exec("")
... print(x)
... print(y)
...
>>> example()
local
local
So apparently, locals() mutations CAN affect name lookups. Happens the
same way in Jython, too.
This is quite a rabbit-hole.
ChrisA
More information about the Python-list
mailing list