22 October 2010

Python singleton design pattern

How to define a class with a singleton instance? From http://python.org/dev/peps/pep-0318/, here is how:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...


However, you can also achieve singleton without such clumsy code - use python module. See here:

http://tinyurl.com/yeotybq.

A module with functions and module scope variables is handy for such purpose! So no OOP is needed?! However, be cautious with singleton design pattern. Watch this blog post from google testing blog.

No comments: