are free variables part of the local dict ?
Giorgi Lekishvili
gleki at gol.ge
Mon Jan 14 19:07:00 EST 2002
Hi!
What you'd say about this?
>>> def foo(i):
global x
x=1
def bar(i):
x=x+i
print locals()
bar(i)
Or, have I undestood you in a wrong manner?
Grtz,
Giorgi
>>> foo(2)
Traceback (innermost last):
File "<pyshell#22>", line 1, in ?
foo(2)
File "<pyshell#21>", line 7, in foo
bar(i)
File "<pyshell#21>", line 5, in bar
x=x+i
UnboundLocalError: Local variable 'x' referenced before assignment
>>> def foo(i):
global x
x=1
def bar(i):
x
x=x+i
print locals()
bar(i)
>>> foo(2)
Traceback (innermost last):
File "<pyshell#30>", line 1, in ?
foo(2)
File "<pyshell#29>", line 8, in foo
bar(i)
File "<pyshell#29>", line 5, in bar
x
UnboundLocalError: Local variable 'x' referenced before assignment
>>>
Cesar Douady wrote:
> 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