instances {def singleton(aclass)on decoration def oncall(*args**kwargs)on instance creation if aclass not in instancesone dict entry per class instances[aclassaclass(*args**kwargsreturn instances[aclassreturn oncall to use thisdecorate the classes for which you want to enforce single-instance model (for referenceall the code in this section is in the file singletons py)@singleton class persondef __init__(selfnamehoursrate)self name name self hours hours self rate rate def pay(self)return self hours self rate person singleton(personrebinds person to oncall oncall remembers person @singleton class spamdef __init__(selfval)self attr val spam singleton(spamrebinds spam to oncall oncall remembers spam bob person('bob' print(bob namebob pay()really calls oncall sue person('sue' print(sue namesue pay()samesingle object spam(val= spam( print( attry attrone personone spam nowwhen the person or spam class is later used to create an instancethe wrapping logic layer provided by the decorator routes instance construction calls to oncallwhich in turn ensures single instance per classregardless of how many construction calls are made here' this code' output ( prints extra tuple parentheses) :\codepython singletons py bob bob coding alternatives interestinglyyou can code more self-contained solution here if you're able to use the nonlocal statement (available in python onlyto change enclosing scope namesas described earlier--the following alternative achieves an identical effectby using one enclosing scope per classinstead of one global table entry per class it works the same decorators