Skip to content

Instantly share code, notes, and snippets.

@keuv-grvl
Created May 14, 2025 14:04
Show Gist options
  • Save keuv-grvl/b97e6c6865bd6f8dbaa5fb7335295dc3 to your computer and use it in GitHub Desktop.
Save keuv-grvl/b97e6c6865bd6f8dbaa5fb7335295dc3 to your computer and use it in GitHub Desktop.
Singleton pattern
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class MyClass(metaclass=Singleton):
def __init__(self):
self.a = 234
aa = MyClass()
aa.val # 234
bb = MyClass()
bb.val = 654
aa.val # 654
id(aa) == id(bb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment