Singleton is one of the well known design pattern.
In python, most of us use the Borg Singleton like, which is not a true Singleton, since only the ‘state is shared’. In fact, you use distinct objects but they share the same __dict__.
Yesterday, i played a bit w/ python metaclass. Beside this can be really usefull under certain condition, i discover that you can build a Borg with that too :)
class Single_imp: def __init__(cls,name,base,dict): cls.value = 1 def __call__(cls): return cls def setValue(cls,value): cls.value = value class Single: __metaclass__ = Single_imp a = Single() b = Single() print a print b a.setValue(10) print b.value
and the result:
<__main__.Single_imp instance at 0x401eb96c> <__main__.Single_imp instance at 0x401eb96c> 10
Ok .. the code looks strange.. and not a true Singleton .. but how can i build a real true in Python ?
__new__ allows you do fairly simply create a singleton. I think it goes like:
def __new__(cls):
_ try:
_ _ return cls._singleton
_ except AttributeError:
_ _ s = cls._singleton = object.__new__(cls)
_ _ return s
Or you can do:
class _SingletonClass: …
_TheSingleton = _SingletonClass
def SingletonClass():
_ return _TheSingleton
The last one is my preferred solution ;)
Have a look at: http://c2.com/cgi/wiki?PythonSingleton
for many many Singleton Python Implementation (including one w/ metaclasses)