Questions about `locals` builtin

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 27 03:13:48 EST 2018


On Mon, 26 Feb 2018 17:05:46 -0800, Dan Stromberg wrote:

[...]
> I don't have IronPython handy, but according my (quite possibly flawed)
> test program, locals() is a copy on CPython 3, CPython 2, Pypy3, Pypy,
> Jython and MicroPython.
> 
> I didn't see any interpreters that returned the namespace itself.
> 
> What am I missing?

Interesting... it seems that Jython is less consistent than I remembered. 
Here is my test function:

def test():
    y = 2
    ns = locals()
    ns['x'] = 1
    ns['y'] = 1
    print(x, y)
    return
    # Fool the compiler into treating x as a local.
    if False: x = 999


In Jython 2.5, it prints (1, 2). So assigning to locals creates a new 
local variable (x) but doesn't update an existing one (y).

In CPython, I get:

UnboundLocalError: local variable 'x' referenced before assignment

in versions 3.5, 2.7, 2,5, 2,4 and even 1.5 (it's just a regular 
NameError in 1.5).

I broke my IronPython installation, but my recollection is that it would 
print (1, 1). (That's what I thought Jython did too, but I was mistaken.)

So correction is noted: in Jython, at least, locals() is not the 
namespace itself, but some sort of weird proxy to it.


-- 
Steve




More information about the Python-list mailing list