Skip to content

Instantly share code, notes, and snippets.

@BuildWithLal
Last active September 28, 2020 20:10
Show Gist options
  • Save BuildWithLal/3938daf1470a3b7ed7d167976a329638 to your computer and use it in GitHub Desktop.
Save BuildWithLal/3938daf1470a3b7ed7d167976a329638 to your computer and use it in GitHub Desktop.
Create a singleton class using Python 3
class Singleton(object):
def __new__(cls):
if not hasattr(cls, 'instance') or not cls.instance:
cls.instance = super().__new__(cls)
return cls.instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2) # True
print(obj1 == obj2) # True
print(type(obj1) == type(obj2)) # True
print(id(obj1) == id(obj2)) # True
@lucrib
Copy link

lucrib commented Jul 18, 2018

Thank you.
More resonable than this example: https://gist.github.com/lalzada/3938daf1470a3b7ed7d167976a329638

@EstebanJoaquinIgnacio
Copy link

Cool 👍
Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment