While there are many alternate implementations of the Singleton pattern available, I decided to offer my own anyway.
1 2 3 4 5 6 7 8 9 10 11 12 | class Singleton(type):
"""Creates a unique instance of classes that use Singleton as
their metaclass.
"""
def __new__(cls, name, bases, d):
def __init__(self, *args, **kw):
raise TypeError("cannot create '%s' instances" %
self.__class__.__name__)
instance = type(name, bases, d)()
instance.__class__.__init__ = __init__
return instance
|
Used as a metaclass, Singleton replaces a class with a unique class instance. Any subsequent calls to the class's constructor will result in an exception, as the constructor is overwritten immediately after the unique instance is created. I can't think of many instances where someone might accidentally call the constructor, but a Singleton made with this metaclass should behave similarly to the built-in None object. One problem introduced here is that inheritance is broken, but that is more of a problem of the Singleton pattern than of this recipe.