Skip to content

Instantly share code, notes, and snippets.

@mdippery
Last active December 12, 2021 03:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdippery/037d6a9a2fb433f6bd2160c6b41cebb4 to your computer and use it in GitHub Desktop.
Save mdippery/037d6a9a2fb433f6bd2160c6b41cebb4 to your computer and use it in GitHub Desktop.
Creating a Singleton in Python
class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls.instance
class MySingleton(object):
__metaclass__ = Singleton
a = MySingleton()
b = MySingleton()
c = MySingleton()
print a is b
print b is c
print a is c
print
print a == b
print b == c
print a == c
print
print hash(a)
print hash(b)
print hash(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment