Skip to content

Instantly share code, notes, and snippets.

@hnrck
Last active June 17, 2020 10:18
Show Gist options
  • Save hnrck/ee0479e46e66f7ae65d33aae558ed2fc to your computer and use it in GitHub Desktop.
Save hnrck/ee0479e46e66f7ae65d33aae558ed2fc to your computer and use it in GitHub Desktop.
Python singleton design pattern
from .singleton import Singleton
class Example(metaclass=Singleton):
"""
Example class.
"""
pass
def main():
""" Main function """
onj_1 = Example()
obj_2 = Example()
assert obj_1 is obj_2
if __name__ == '__main__':
main()
"""
Singleton design pattern
"""
class Singleton(type):
""" Singleton metaclass """
def __init__(cls, name, bases, attrs, **kwargs):
super().__init__(name, bases, attrs, **kwargs)
cls._instance = None
def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment