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 ?