unintuitive for-loop behavior

Chris Angelico rosuav at gmail.com
Sun Oct 2 01:06:37 EDT 2016


On Sun, Oct 2, 2016 at 3:19 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> In IronPython, you could have the following occur in a function locals, just
> as it could happen CPython for globals:
>
> - delete the name binding "x"
> - which triggers a dictionary resize
> - bind a value to x again
> - because the dictionary is resized, the new "slot" for x is in a
>   completely different position of the dictionary to the old one
>
> There is no user-visible difference between these two situations. Your code
> works the same way whether it is executed inside a function or at the
> global top level, whether functions use the CPython local variable
> optimization or not.

Hmm, interesting. I don't have IronPython here, but maybe you can tell
me what this does:

print(str)
str = "demo"
print(str)
del str
print(str)

and the same inside a function. In CPython, the presence of 'str =
"demo"' makes str function-local, ergo UnboundLocalError on the first
reference; but globals quietly shadow built-ins, so this will print
the class, demo, and the class again. If IronPython locals behave the
way CPython globals behave, that would most definitely be a
user-visible change to shadowing semantics.

ChrisA



More information about the Python-list mailing list