question about globals vars...

Sean 'Shaleh' Perry shalehperry at
Fri Aug 2 17:24:36 CEST 2002

On 02-Aug-2002 Shagshag13 wrote:
> hello,
> i'm wondering when i should use globals or if i should avoid them by fair
> means...
> - so how do you use them or what mecanism do you use to avoid using them (in
> a class / in a function) ?
> - when you do OO style do you define some kind of parameters class, which you
> instanciate and use ?
> - 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 ?

you often here the battle cry of "no globals".  From my perspective it is a
strong style and safety guideline just like wrapping code in concise functions,
using clear variable names, avoiding goto in languages that support it, etc.

foo = 23

def do_somthing(input):
  num = foo + other

here we have a function called do_something() which accesses a global variable.
Later on you realize that the alogorithm in do_something is simlar to one you
need for a current project so you cut and paste the function.  This is when you
notice the global because it is no longer available.  globals create
dependencies and uncertainties which is a big part of why they are not

There's another reason in python -- accessing a global is slower than accessing
a local.

As to your question of "when should/can I use one" I think the best answer is
there is no good answer.  Use one when it seems like the right choice. 
Document the fact that a class/function/whatever needs the global.  Often times
globals are used early in design and then replaced later.

Some people go out of their way to avoid globals and just as often have a
global in spirit but not name.  Like any other guideline following it without
thinking can lead to just as much of a mess.

More information about the Python-list mailing list