Singletonize any class

pythopian 2 Tallied Votes 231 Views Share

This is one simple way to emulate a singleton class on behalf of a normal class. (A singleton class is a class with at most one instance.)

The implementation does not emulate a class 100% (for example it lacks the special attributes lile __dict__ or __bases__), but it should be absolutely sufficient in most common cases.

def Singleton(cls):
    instance = []
    def create(*args, **kw):
        if not instance:
            instance.append(cls(*args, **kw))
        return instance[0]
    return create

# Test:

TheList = Singleton(list)

def test2():
    mylist1 = TheList([1,2,3])
    mylist2 = TheList()
    print mylist1, mylist2
    mylist1.append(4)
    del mylist1[1]
    print mylist1, mylist2

>>> test2()
[1, 2, 3] [1, 2, 3]
[1, 3, 4] [1, 3, 4]