Singleton class: what is the purpose?

Aldo Cortesi aldo at nullcube.com
Thu Jun 5 08:07:11 EDT 2003


Thus spake Gerrit Holl (gerrit at nl.linux.org):

> What is a singleton class? What is the purpose of a
> singleton class?
> 
> On the web, I have found that a singleton class allows
> only one instance.  Is that correct? 

Yep, that's right - the Singleton pattern is used to make
sure that only one instance of a given class exists. 


> If so, it should be easily implementable with:
> 
>  20 >>> class Singleton(object):
>  20 ...  instances = []
>  20 ...  def __init__(self):
>  20 ...   if len(self.__class__.instances) == 0:
>  20 ...    self.__class__.instances.append(self)
>  20 ...   else:
>  20 ...    raise Exception("No way jose!")

Almost, but this is really only half an implementation of
the Singleton pattern. A real implementation has to do two
things:
    - Ensure that only one instance exists
    - Make that instance available in some global way

See here for some discussion of various implementation
strategies:

http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52558


> But what is the purpose of a Singleton class?

There are lots of circumstances in which the Singleton
pattern comes in handy. For instance, you may have a program
that should have only one connection to a database, or a
system where only one print spooler should exist. Or,
perhaps you want to share a single instance of a commonly
used, but expensive to create, object between the various
parts of your application. For a more in-depth discussion of
the use (and abuse) of the Singleton Pattern see the
excellent c2 wiki:

http://c2.com/cgi/wiki?SingletonPattern


You should also note that the Singleton pattern has recently
fallen out of vogue with the Python in-crowd. If you're hip,
and in-the-know, you're supposed to advocate the Borg
pattern. The name is a pune or play on words - whereas the
Singleton pattern means that There Can Only Be One (i.e.
only one instance can exist), the Borg pattern means that
You Will Be Assimilated (i.e. many instances can exist, but
all have the same state). The skeleton for a Borg-ised class
looks like this: 

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state

As you can see, a single __dict__ is shared between all
instances. In practice, this achieves much the same purpose
as the Singleton pattern - object identity may differ from
instance to instance, but since state is shared, all
instances act exactly the same. 


Finally, many people forget that Python has something very
much like the Singleton concept built in - modules. Python
ensures that code in module scope is only executed once
(unless you force a reload), no matter how many times a
module is imported....




Cheers,



Aldo




-- 
Aldo Cortesi
aldo at nullcube.com
http://www.nullcube.com






More information about the Python-list mailing list