Generic singleton

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 5 04:32:46 CET 2010


On Thu, 04 Mar 2010 12:21:26 +0000, Duncan Booth wrote:

> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote:
> 
>> On Wed, 03 Mar 2010 19:54:52 +0100, mk wrote:
>> 
>>> Hello,
>>> 
>>> So I set out to write generic singleton, i.e. the one that would do a
>>> singleton with attributes of specified class. At first:
>> 
>> Groan. What is it with the Singleton design pattern? It is one of the
>> least useful design patterns, and yet it's *everywhere* in Java and C++
>> world.
> 
> It is also *everywhere* in the Python world. Unlike Java and C++, Python
> even has its own built-in type for singletons.
> 
> If you want a singleton in Python use a module.

I was wondering who would be the first to point that out :)

You are, of course, correct that the preferred way to solve the Singleton 
problem is with a module. (The other preferred way is with the Borg 
pattern, which is kind of a reverse-Singleton.) Using classes works too: 
so long as you do not instantiate it, but use it as an object in its own 
right, a class is also a singleton.

However, I don't think it's quite right to say that modules *are* 
Singletons, although I accept that this is now getting into a tedious 
argument about terminology. A singleton is an instance of a class which 
can only have a single instance. This is not true of modules:

>>> import string, math
>>> type(string) is type(math)
True
>>> string is math
False

Wikipedia points out that the Singleton pattern is normally understood to 
exclude static structures which merely happen to be created once:

"Note the distinction between a simple static instance of a class and a 
singleton..."

http://en.wikipedia.org/wiki/Singleton_pattern

Each individual module is a static instance of the module class which 
merely happens to be instantiated once. (You can subvert Python's import 
machinery to create multiple copies of a module, but normally this 
doesn't happen.) So *technically* modules are not singletons, although 
they behave just like them and give all the benefits, and disadvantages, 
of such. And as you say, the preferred Pythonic solution to the 
requirement for a Singleton is usually a module.

Python does have it's own singletons, like None, True and False. For some 
reason, they behave quite differently: NoneType fails if you try to 
instantiate it again, while bool returns the appropriate existing 
singleton:

>>> NoneType = type(None)
>>> NoneType()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot create 'NoneType' instances
>>> bool(45)
True


I wonder why NoneType doesn't just return None?


-- 
Steven



More information about the Python-list mailing list