Singleton class: what is the purpose?

Jack Diederich jack at
Thu Jun 5 16:52:55 CEST 2003

On Thu, Jun 05, 2003 at 02:30:08PM +0200, Just wrote:
>   >>> class Singleton(object):
>   ...     _instance = None
>   ...     def __new__(cls, *args, **kwargs):
>   ...         if cls._instance is None:
>   ...             cls._instance = object.__new__(cls)
>   ...         return cls._instance
cannonical as of 2.2.x (Aahz in another reply says the cannonical way
is to use modules, I'm not sure what he means, I like it the above way).

> > But what is the purpose of a Singleton class?
> In my case it was basically a euphemism for a global variable ;-)

Singleton is the most abused Design Pattern for this reason, you can still
use globals all over the place (bad practice) but now say "I'm using
Design Patterns!".  A good singleton is something there can only be one
of by definition.  For instance, in a TCP/IP based server there is only
one client per connection so a valid singleton would be a IP/port pair
of the other guy.  If running a world simulation, Earth() would return
the same object every time as well.

Be careful when putting resources (like database connections) in singletons,
"It's a Trap!"  You end up with code that just assumes the resource will
always be valid and available, when in fact it isn't.  My rule of thumb
is that if you can't initialize the singleton _first thing_ without depending
on anything that isn't also a singleton then you are making a global and
not a singleton.


More information about the Python-list mailing list