I've seen a few ways to create singletons in Python, but they all seem to have some drawback or another. I just invented a way myself, and I'd like to know what's wrong with it :).
class Singleton(object): def __init__(self, cls, *args, **kwargs): self.instance = cls(*args, **kwargs) def blocked(doppelganger, *args, **kwargs): raise RuntimeError("singleton") cls.__init__ = blocked def getInstance(self): return self.instance class A(object): def __init__(self, x): self.x = x a = Singleton(A, 10)
This works by handing a class to
Singleton, which then instantiates it, then hobbles it by causing its constructor to raise a runtime exception. The main drawback I can see is that this pattern will only prevent more instances from being created, but doesn't guarantee that there is only one instance out there. It can also hobble any class at all, which is probably a bad idea.
These two drawbacks can be solved by un-abstracting the behavior into each class that wants to be a singleton. For example, the definition of
blocked and its assignment to
self.__init__ can be the last lines of
A's constructor. Then
A can only ever be instantiated once, though some other mechanism would need to place the single instance somewhere where clients can get to it.
Are there any other drawbacks to this approach?