Skip to content

Instantly share code, notes, and snippets.

@bhaskarkc
Created April 19, 2021 11:58
Show Gist options
  • Save bhaskarkc/f150daa98898a148b84bc772651fe191 to your computer and use it in GitHub Desktop.
Save bhaskarkc/f150daa98898a148b84bc772651fe191 to your computer and use it in GitHub Desktop.
Python singleton class.
class Singleton:
def __init__(self, cls):
self._cls = cls
def Instance(self):
try:
return self._instance
except AttributeError:
self._instance = self._cls()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `Instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._cls)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment