953,275 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Singletonize any class

By pythopian on Nov 12th, 2009 2:59 am

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]

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: