singleton decorator

Andre Meyer meyer at acm.org
Mon Aug 7 19:33:31 EDT 2006


While looking for an elegant implementation of the singleton design pattern
I came across the decorator as described in
PEP318<http://www.python.org/dev/peps/pep-0318/>
.
Unfortunately, the following does not work, because decorators only work on
functions or methods, but not on classes.

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

@singleton
class MyClass:
    ...


Am I missing something here? What is the preferred pythonic way of
implementing singleton elegantly?

Thanks for your help
André
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20060808/8924bafd/attachment.html>


More information about the Python-list mailing list