Globals or objects?

Duncan Booth duncan.booth at invalid.invalid
Thu Feb 21 08:47:35 EST 2008


MartinRinehart at gmail.com wrote:

> I had a global variable holding a count. One source Google found
> suggested that I wouldn't need the global if I used an object. So I
> created a Singleton class that now holds the former global as an
> instance attribute. Bye, bye, global.
> 
> But later I thought about it. I cannot see a single advantage to the
> object approach. Am I missing something? Or was the original global a
> better, cleaner solution to the "I need a value I can read/write from
> several places" problem?

A singleton is simply another form of global. The benefit of a singleton 
is that it can be used to encapsulate several related values and methods 
in a single globally accessible space. The easiest way in Python to 
implement a singleton is just to use a module: all modules are 
singletons and there is a defined mechanism (import) for accessing them.

It sounds as though you simply replaced a value stored in a singleton 
object (global in a module) with a value stored in a singleton object 
(attribute of your class) which is referenced from a singleton object 
(your module).

The real benefit from using an object comes when you stop making it a 
singleton. Create it at some high level in your code and pass it around 
as a parameter, or hold a reference to it in some other object which is 
passed around. When you do this you no longer have a global, and the 
benefits you get include:

* for your counter example, you can have multiple counters counting 
different things without having to duplicate counter code for each thing 
you want to count.

* it becomes much easier to write tests for your code, because each test 
can create its own context and be completely independant from the other 
tests. e.g. you can test a generic counter without having to know you 
are testing the foo counter or the bar counter, and you can test 
something which counts foos without having to worry that other tests may 
already have counted some foos.

There is another lesser (and Python specific) benefit to storing a value 
as an attribute of a class rather than a global in a module: if you 
later want to intercept assignments to the attribute you can turn it 
into a property, but doing the same thing on a module is much harder. 



More information about the Python-list mailing list