Python singleton pattern

After a quick search where I didn’t find a singleton implementation for new-style classes in Python. For classic classes there’s the excellent Borg pattern. So here’s singleton for new-style classes:

class Singleton(object):

__instance = None

@classmethod
def getInstance(cl):
"""
Get the global engine instance or create one if none exists yet.
"""
if cl.__instance is None:
cl.__instance = cl()

return cl.__instance

Leave a Reply

Your email address will not be published. Required fields are marked *