[Tutor] local variables

Gregor Lingl glingl@aon.at
Tue, 13 Aug 2002 12:12:07 +0200


Hi! Please look at the following interactive session:

 >>> x = 5
 >>> def test():
    print x

   
 >>> test()
5
 >>> def test():
    print x
    x = x + 1

   
 >>> test()
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in ?
    test()
  File "<pyshell#19>", line 2, in test
    print x
UnboundLocalError: local variable 'x' referenced before assignment

##### So the python interpreter has some knowledge about the existence of x
##### This seems to be established with the execution of the 
def-statement (?)

 >>> def test():
    print vars()
    x = 1
    print x
    x = x + 1
    print vars()

   
 >>> test()
{}
1
{'x': 2}
 >>>

##### But this knowledge apparently doesn't show up in vars().

My question: is there a function, an attribute, or whatever, that 
delivers the
fact, that x is a local variable at a point of execution where the
assignment still hasn't taken place? Or - in other words - that delivers 
a list
of all local variables - including those which still haven't got 
assigned a value?

Gregor