Generic singleton

mk mrkafk at gmail.com
Wed Mar 3 13:54:52 EST 2010


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:

class Singleton(object):

     instance = None

     def __new__(cls, impclass, *args, **kwargs):
         if cls.instance is None:
             cls.instance = impclass.__new__(impclass, *args, **kwargs)
         return cls.instance

s1 = Singleton(dict)
s2 = Singleton(dict)

s1['spam']='wonderful'

print s1, s2
print id(s1) == id(s2)


Now, this works. But this obviously doesn't allow class of singleton to 
be changed, or a new singleton for another class to be created. So:


class Singleton(object):

     instd = {}

     def __new__(cls, impclass, *args, **kwargs):
         impid = id(impclass)
         if not cls.instd.has_key(impid):
             cls.instd[impid] = impclass.__new__(impclass, *args, **kwargs)
         return cls.instd[impid]

s1 = Singleton(dict)
s2 = Singleton(dict)
s1['spam']='wonderful'


s3 = Singleton(list)
s4 = Singleton(list)
s3.append('eggs')

print id(s1) == id(s2)
print id(s3) == id(s4)

print s1, s2, s3, s4


Questions:

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

hashable
..
     All of Python’s immutable built-in objects are hashable, while no 
mutable containers (such as lists or dictionaries) are.

Well ok, hashable they're not; but apparently at least dict and list 
have id()?

 >>> id(list)
135709728
 >>> id(dict)
135714560
 >>> id(dict)
135714560
 >>> c=dict
 >>> id(c)
135714560


2. Drawbacks?

3. Better/fancier way to do this?

Regards,
mk






More information about the Python-list mailing list