[Tutor] Question about 'scopes'

alan.gauld@bt.com alan.gauld@bt.com
Tue Mar 25 09:14:02 2003


> Since this would deviate from 'normal', under what kinds of 
> conditions might one want to declare a variable as a global 
> variable rather than local? 

As few as possible. Global variables are generally held to 
be a bad thing in software engineering. There are very few(none?) 
cases when you *must* use global variables, but occasionally 
they help keep the code less cluttered. Use them sparingly 
is the golden rule...

> so what might influence someone to declare a variable globally?

If you have a number of values that must be persistent between 
function calls you might declare them as variables. You can then
call the functions and the set value is available to the next 
function in the chain.

However a better way of doing this is to pass the global variables 
into the functions as parameters and return the new values from 
the function. Like so:

x = 2
y = 8

def f(anX,aY):
   i = anX**2
   j = aY - 1
   return i,j

def g():   # 'bad' version
   global x,y
   x = x**2
   y = y - 1

x,y = f(x,y)
print x,y  #--> 4, 7
g()
print x,y  #--> 16, 6

Both f() and g() have the same result but f() does it explicitly 
while g() does it silently via the global statement.

Once you start using classes and OOP you will find that these 
provide an even better way of avoiding globals almost entirely.
But I suspect you're not quite ready for OOP just yet.

Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/