global variables

Erik Jones erik at myemma.com
Tue Oct 2 19:34:04 EDT 2007


On Oct 2, 2007, at 5:20 PM, TheFlyingDutchman wrote:

> Does anyone know how the variables label and scale are recognized
> without a global statement or parameter, in the function resize() in
> this code:
>
>
>
> #!/usr/bin/env python
>
> from Tkinter import *
>
> def resize(ev=None):
>       label.config(font='Helvetica -%d bold' % \
>           scale.get())
>
>
> top = Tk()
> top.geometry('250x150')
>
> label = Label(top, text='Hello World!',
>     font='Helvetica -12 bold')
> label.pack(fill=Y, expand=1)
>
> scale = Scale(top, from_=10, to=40,
>      orient=HORIZONTAL, command=resize)
> scale.set(12)
> scale.pack(fill=X, expand=1)
>
> quit = Button(top, text='QUIT',
>     command=top.quit, activeforeground='white',
>     activebackground='red')
> quit.pack()
>
> mainloop()

It's tricky.  Basically, you only need to use the global statement if  
you intend binding operations (assignments) on the variable name and  
want those to affect the global variable.  If you perform binding  
operations without the global statement it is assumed that you are  
defining a local variable.

class foo(object):
	def foofoo(self):
		print 7

def showfoo():
	f.foofoo()

f = foo()
showfoo()
print f

outputs:

7
<__main__.foo object at ... >

with the same class:

def showfoo():
	global f
	f.foofoo()
	f = 6

f = foo()
showfoo()
f
  outputs:

7
6

with the same class again:

deff showfoo():
	f.foofoo()
	f = 6

f = foo()
showfoo()

outputs:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 2, in showfoo
UnboundLocalError: local variable 'f' referenced before assignment

The difference in the last one is that when showfoo() is compiled the  
assignment to f without any global statement makes f a local variable  
and a method is called on it before it is bound which results in the  
exception.

Erik Jones

Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com





More information about the Python-list mailing list