Skip to content

Instantly share code, notes, and snippets.

@Ananto30
Created March 22, 2020 12:30
Show Gist options
  • Save Ananto30/70750cd6d48a9fd306287db9c456061c to your computer and use it in GitHub Desktop.
Save Ananto30/70750cd6d48a9fd306287db9c456061c to your computer and use it in GitHub Desktop.
Singleton implementation in Python
class SingletonMeta(type):
_instance = None
def __call__(self):
if self._instance is None:
self._instance = super().__call__()
return self._instance
class Singleton(metaclass=SingletonMeta):
# Now implement you singleton class
def some_business_logic(self):
pass
if __name__ == "__main__":
s1 = Singleton()
s2 = Singleton()
# You can check they are both same instance
assert(id(s1) == id(s2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment