A
Andre Meyer
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é
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é