Welcome, guest | Sign In | My Account | Store | Cart
def singleton(theClass):
    """ decorator for a class to make a singleton out of it """
    classInstances = {}

    def getInstance(*args, **kwargs):
        """ creating or just return the one and only class instance.
            The singleton depends on the parameters used in __init__ """
        key = (theClass.__name__, args, str(kwargs))
        if key not in classInstances:
            classInstances[key] = theClass()
        return classInstances[key]

    return getInstance


# Example

@singleton
class A:
    def __init__(self, key=None):
        self.key = key

a1 = A()
a2 = A()
print(a1, a2)
assert a1 == a2

a3 = A(10)
a4 = A(10)
print(a3, a4)
assert     a3 == a4
assert not a3 == a2

a5 = A("hello")
a6 = A("hello")
print(a5,a6)
assert     a5 == a6
assert not a6 == a4
assert not a6 == a2

History