are free variables part of the local dict ?

Cesar Douady cesar.douady at asim.lip6.fr
Mon Jan 14 07:04:43 EST 2002


in :

def foo():
    x=1
    def bar():
        x
        print locals()
    bar()
foo()

the result is "{}", indicating that x is not in locals(). But in :

def foo():
    x=1
    def bar():
        x
        y=1
        print locals()
    bar()
foo()

the result is "{'y':1, 'x':1}", indicating that the presence of y has made
x part of locals().

Note also that in :

def foo():
    x=1
    class bar:
        x
        y=1
    print dir(bar)
foo()

the result is "['__doc__', '__module__', 'y']", showing that x was not
included.

My comprehension is that free variables should never be part of locals()
and that the second output is a bug. However, from looking at the
interpreter code, it seems that this is done on purpose (i.e. free vars
are part of the local dict only for functions, the difference between the
first 2 codes still looks like a bug).

Before sending a bug report on such a tricky subject, I would appreciate
getting various opinions.

Cesar.



More information about the Python-list mailing list