[Tutor] Global variables

Alan Gauld alan.gauld at freenet.co.uk
Tue Aug 15 09:37:05 CEST 2006


> 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...
>
> 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.

The names have very little to do with it, the danger of global 
variable
use is the reliance on side-effects and the tight coupling that you
introduce between the calling module and the called module.
Changes to the state of the calling module in an unpredictable
manner lead to subtle bugs which are extremely hard to see and fix.

> increase errors due to confusion of global and local variables.

Confusion of names is of very little import, that really isn't the 
issue.

> I would never have a local variable with the same name as the global
> variable.

Again thats not a problem.

> 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.

I'd be very very doubtful that its a bug in Python.
Python is very well tested and while occasionally bugs do surface,
the type of bug you are describing is extremely unl;ikely to have
remained hidden. It is far more likely to be an error in the code
or in the data.

> My routine strongfac calculates a value for fac in the subroutine, 
> and the
> calling routine picks up a different vaalue.
>
> An illustration.
>
> In strong fac:
>
> fac = [1,2,3]
> print fac
> return fac
>
> in fermat:
>
> fac = strongfac(z)
> print fac
>
> prints [0,0,0]
>
> And most of the time it does not misbehave like this.
>
> It is only occasionally, and consistently with certain numbers to be
> factored.

All of which points to an error in the code not in Python.
The way Python is written it is virtually never going to result in
that kind of error dependant on data values. That might happen
is if the values are very close to zero and a type conversion
occurs, but otherwise I'm very dubious about a Python bug
of that type.

Alan G. 



More information about the Tutor mailing list