question about globals vars...

Will Stuyvesant hwlgw at
Fri Aug 2 22:04:55 CEST 2002

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

That is a personal matter.  There are people who say you should avoid
them indeed.  There are other people who say those people are wrong. 
Here I will give you my opinion on them.

If you try to avoid them you will find you have to think harder about
your code, which will result in better code often.  But global
variables do have their use: if you find you have to think -too- hard
it is often better to use them (:-)

> - so how do you use them or what mecanism do you use to avoid using them (in a class / in a function) ?

Personally I use them in very small scripts often.  If you have a big
project with several source files I put all the globlas in one file
and have all the other files import that file, for example

> - when you do OO style do you define some kind of parameters class, which you instanciate and use ?

I try to avoid OO style often, especially inheritance.  Meaning that
OO inheritance often breaks encapsulation.
For example you have a class S that represents a stack, with methods
push(x) and pop() and a numberOfItems attribute.  Now if you inherit
from that class and you define a method multipop(n, x) returning a
list of items with length n you have a problem.  Can you call pop(x) n
times or not?  Is pop(x) updating the numberOfItems attribute?  To
find out you would have to look at the source code definition of pop()
OO style has good points but is often overused.

> - is it a good idea to use a global as a flag : put it to 0 or 1 in main and then testing in other functions/class and changing way
> of acting according to flag value ?
> - or should i prefer to only use globals as default value for other vars ?

Global variables are good when they make your source code more clear.

Just my .02

More information about the Python-list mailing list