[Python-Dev] PEP 318: Singleton decorator
Ka-Ping Yee
python-dev at zesty.ca
Tue Mar 30 06:17:08 EST 2004
Hi folks.
Earlier messages suggested a nice singleton decorator, which is shown
in the draft PEP:
def singleton(cls):
return cls()
class MyClass [singleton]:
...
This has been mentioned as an argument against requiring or recommending
that decorators accept and return callables.
But i don't think this is a good way to write a singleton, because then
the user of the class has to get instances by saying "MyClass" instead
of "MyClass()". Better would be:
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
Then, code that gets an instance makes more sense. MyClass() still
instantiates MyClass -- it just always returns the same instance.
I respectfully suggest that the PEP use the latter implementation in
its singleton example instead.
-- ?!ng
More information about the Python-Dev
mailing list