Skip to content

Instantly share code, notes, and snippets.

@goutomroy
Last active October 11, 2020 23:13
Show Gist options
  • Save goutomroy/c925b1316bd9e7ec2cf9b1e4c183f5f4 to your computer and use it in GitHub Desktop.
Save goutomroy/c925b1316bd9e7ec2cf9b1e4c183f5f4 to your computer and use it in GitHub Desktop.
A singleton decorator for python classes.
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