[Tutor] Global variables

Luke Paireepinart rabidpoobear at gmail.com
Tue Aug 15 02:18:34 CEST 2006

Kermit Rose wrote:
> From: Alan Gauld 
> Date: 08/14/06 18:42:41 
> To: Kermit Rose; Luke Paireepinart 
> Cc: tutor at python.org; Danny Yoo 
> Subject: Re: [Tutor] Global variables 
> That may be true but you will make your code much less reusable 
> and much more error propne in the process. There are good reasons 
> why global variables are considered evil... 
> *****
> I know that global variable usage can be abused.
> But in fact I use the same variable names  in the subroutine parameter list
> as in the calling routine for every function in the module.
> So I believe that in this case global variables would be useful and not
> likely to
> increase errors due to confusion of global and local variables.
> I would never have a local variable with the same name as the global
> variable.
It sounds like you should make a Factoring class and have whichever
variables are similar for all functions be variables specific to the 
class instance
(I forgot the word for this)

Something like:

Class Factoring(object):
    def __init__(self):
       self.var1 = ['a','b','c']
       self.var2 = 5
       self.var3 = (0)

    def method1(self):
       print self.var1,self.var2
    def method2(self):
       print self.var2,self.var3

fac = Factoring()

the output would be

Thus you prevent global namespace pollution.
> But in this case, it's only because of an apparent bug in Python that want
> to 
> bypass that I'm considering the use of global variables.
You probably shouldn't claim there's a bug in Python unless you're sure 
(I.E. have a snippet of code
that reproduces the bug that you'll share with us)
> My routine strongfac calculates a value for fac in the subroutine, and the
> calling routine picks up a different vaalue.
do you think you could use more conventional terminology like 'function' 
and such?
I don't understand what you mean by the subroutine of the routine.
def routine():
    def subroutine():
       print 'hi'

Is that what you mean?
or by 'subroutine' do you mean 'loop inside of function'?

By your terminology, if there's a routine that calls strongfac, doesn't 
that mean
strongfac is a subroutine?  which would mean that the value for fac is 
calculated in the subroutine of the subroutine of the calling routine?

> An illustration.
> In strong fac:
> fac = [1,2,3]
> print fac
> return fac
> in fermat:
> fac = strongfac(z)
> print fac
> prints [0,0,0]
what is 'z'?  a random parameter?
can you give us a cut-down version of your code that just reproduces this
erratic behavior you're having a problem with?

> And most of the time it does not misbehave like this.
if random.randint(0,5) < 3:
> It is only occasionally, and consistently with certain numbers to be
> factored.
so with certain numbers it always occurs, with other numbers it 
sometimes occurs?
> Kermit   <  kermit at polaris.net >

More information about the Tutor mailing list