Generic singleton

Duncan Booth duncan.booth at invalid.invalid
Thu Mar 4 07:21:26 EST 2010


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.

So the OP's original examples become:

--- file singleton.py ---
foo = {}
bar = []

--- other.py ---
from singleton import foo as s1
from singleton import foo as s2
from singleton import bar as s3
from singleton import bar as s4

... and then use them as you wish.



-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list