Locals [was Re: unintuitive for-loop behavior]
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Oct 3 00:09:00 EDT 2016
On Monday 03 October 2016 12:42, Steve D'Aprano wrote:
> Yes the local would have been created, but you wouldn't see it from an
> ordinary lookup of name x. You would need to use
>
> locals()['x']
>
> to see that it exists. For x to return it, you have to convince the compiler
> to use LOAD_FAST bytecode rather than LOAD_whatever.
Sorry, that first sentence is misleading. The question is, can you create local
variables inside a function using locals()[name]? IronPython and Jython allow
it; CPython doesn't.
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
--
Steven
git gets easier once you get the basic idea that branches are homeomorphic
endofunctors mapping submanifolds of a Hilbert space.
More information about the Python-list
mailing list