scopes? (is: I don't get it ...)

Jack Diederich jack at performancedrivers.com
Thu May 29 08:18:36 EDT 2003


On Thu, May 29, 2003 at 02:02:29PM +0200, Axel Bock wrote:
> 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?

python's motto "explicit is better than implicit" kicks in here,
it isn't sure if you want to create a local variable t2, or increment the
global variable t2 by one.  writing
def testme():
  global t2
  t2 += 1

will do what you want.  Most variables aren't global in python so it throws
a fit assuming you messed up.  In the print statements there is no local
variable t1 or t2, so it is sure that you want to read the globals.

-jack





More information about the Python-list mailing list