Skip to content

Instantly share code, notes, and snippets.

@tweakimp
Last active December 15, 2019 14:02
Show Gist options
  • Save tweakimp/31874dc59334b6967abfcce237942298 to your computer and use it in GitHub Desktop.
Save tweakimp/31874dc59334b6967abfcce237942298 to your computer and use it in GitHub Desktop.
Singleton
class Singleton(type):
"""
Metaclass.
Only allows the creation of one instance, all other tries return
the same instance of the first creation.
Use:
class Test(metaclass=Singleton):
...
"""
def __init__(self, *args, **kwargs):
self.__instance = None
super().__init__(*args, **kwargs)
def __call__(self, *args, **kwargs):
if self.__instance is None:
self.__instance = super().__call__(*args, **kwargs)
return self.__instance
if __name__ == "__main__":
class Test(metaclass=Singleton):
def __init__(self):
print("Initializing Test")
a = Test()
b = Test()
c = Test()
print(a is b)
print(b is c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment