[Python-Dev] locals(), closures, and IronPython...

Terry Reedy tjreedy at udel.edu
Tue Mar 6 01:02:47 CET 2007


"Dino Viehland" <dinov at exchange.microsoft.com> wrote in message 
news:7AD436E4270DD54A94238001769C22276A624C7482 at DF-GRTDANE-MSG.exchange.corp.microsoft.com...
def a():
                x = 4
                y = 2
                def b():
                                print y, locals()
                print locals()
                b()

a()

in CPython prints:

{'y': 2, 'x': 4, 'b': <function b at 0x020726F0>}
2 {'y': 2}

I'm wondering if it's intentional that these don't print dictionaries w/ 
the same contents or if it's more an accident of the implementation.   In 
other words would it be reasonable for IronPython to promote all of the 
locals of a into b's dictionary when both a and b call locals?

==========================================
This version

def a():
    x = 4
    y = 2
    def b():
        print y, locals()
    print locals()
    return b

a()()

has essentially the same output, as it should.  Do you really want the 
binding of 'x' and 'b' to survive the a's return?  I see no reason why a's 
call of locals() should affect this either way.  Which is to say, why the 
compilation of b should be affected by the code that follows it.

This version also has the same output

def a():
    x = 4
    def b():
        print y, locals()
    y = 2
    print locals()
    return b

a()()

whereas this omits y from a's output, but not b's:

def a():
    x = 4
    def b():
        print y, locals()
    print locals()
    y = 2
    return b

a()()

and would also if b were called instead of returned, as in your version. 
So it would not make too much sense for the two printouts to match.

Terry Jan Reedy






More information about the Python-Dev mailing list