question about globals vars...

Bryan Olson fakeaddress at nowhere.org
Sat Aug 3 21:58:11 CEST 2002


Shagshag13 wrote:

 > i'm wondering when i should use globals or if i should avoid them by 
fair means...
[...]


First the good news: module scope is the most globally we can define
things in Python.  The bad news is most of us have probably never seen
useful Python code that avoids this kind of global variable.

Let's look at a trivial example:


def twice(x):
     return x + x

def thrice(x):
     return x + x + x

def six_times(x):
     y = twice(x)
     return thrice(y)


Above we have three global variables: twice, thrice, and six_times.  How
would we describe the function assigned to the name "six_times"?  We
might be tempted to say it returns it's argument times six, but really
it looks up the value assigned to "twice", applies that to it's
argument, then looks up "thrice" etc.  The variables are local to the
module, but other modules can change their assignments.  Thus the
computation performed by the function depends upon every module in the
program.

We could create and assign a more stable function to six_times as:


def _define_six_times():
     _twice = twice
     _thrice = thrice
     def _six_times(x):
         y = _twice(x)
         return _thrice(y)
     return _six_times

six_times = _define_six_times()


We still use global variables in creating the function, and "six_times"
itself is still a global, but the function that is the value of
six_times is independent of any global variables.  It returns six times
its argument no matter what other modules may do.

One might even want to use an idiom like:

def define_funcs():
     def twice(x):
         return x + x
     def thrice(x):
         return x + x + x
     def six_times(x):
         return twice(thrice(x))
     return twice, thrice, six_times

twice, thrice, six_times = define_funcs()


The idiom doesn't really solve the problem since it can only cover
intra-module references.  The names that other modules will import and
use are still global variables.  Perhaps Python should add constants as
an alternative to variables.


--Bryan




More information about the Python-list mailing list