scopes? (is: I don't get it ...)
John Roth
johnroth at ameritech.net
Thu May 29 09:50:28 EDT 2003
"Axel Bock" <news-and-lists at the-me.de> wrote in message
news:pan.2003.05.29.12.02.28.733234 at the-me.de...
> Hi all,
>
> a simple question about modules (and perhaps scopes), illustrated with
a
> simple example.
> Given is the module listed down here:
> test.py:
> t1 = []
> t2 = 0
> def testme():
> print t1
> print t2
> #t2+=1
>
> now I'm doing int the python shell:
> >>> import test
> >>> test.testme()
> []
> 0
> >>>
> great, huh?
> now I remove the comment from line 3 of testme(), and going for it
again:
> >>> reload(test)
> <module 'test' from 'test.py'>
> >>> test.testme()
> []
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "test.py", line 6, in testme
> print t2
> UnboundLocalError: local variable 't2' referenced before assignment
> >>>
> so. WHY???? I mean, print works, so it gets the variable. If I
wouldn't
> know it, I could hardly print the value, right?? So what's the problem
> with the assignment in line 3?
>
> thankful for any help! :-)
As soon as you make the assignment, it's 't2' is a local
variable. It's a local variable in the ***entire*** function
or method, so the reference in the print statement is to
the local variable 't2', not to the module level variable.
John Roth
>
>
> Greetings,
>
> Axel.
More information about the Python-list
mailing list