Generic singleton

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Mar 4 03:14:18 CET 2010


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.

I suspect because it allows people to have all the bugs and difficulties 
of global variables, while still pretending to be virtuous for not using 
global variables. But maybe I'm cynical...

There are a ton of recipes out there for Python Singletons. Don't forget 
to check out the Borg pattern, which gives more or less the same effect 
using a radically different approach.

Then, my advice is to forget all about them. In my experience, I have 
never needed to code my own Singleton class in anything except toy 
examples. YMMV.


> print id(s1) == id(s2)

Or, more concisely:

s1 is s2




> class Singleton(object):
> 
>      instd = {}
> 
>      def __new__(cls, impclass, *args, **kwargs):
>          impid = id(impclass)

Yuck. Why are you using the id of the class as the key, instead of the 
class itself?


class Singleton(object):
    instd = {}
    def __new__(cls, impclass, *args, **kwargs):
        if not impclass in cls.instd:
            cls.instd[impclass] = impclass.__new__(
                impclass, *args, **kwargs)
         return cls.instd[impclass]


> Questions:
> 
> 1. Is this safe? That is, does every builtin class have unique id? I
> have found this in docs:

Why are you limiting yourself to builtin classes?

ALL objects, whether classes or builtins or strings or ints or instances 
of a class you built yourself, have a unique id that lasts for the 
lifespan of the object. But that is certainly not what you care about.


-- 
Steven



More information about the Python-list mailing list