Skip to content

Instantly share code, notes, and snippets.

@curtiscook
Created December 8, 2022 03:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save curtiscook/65d6caf95b5834b82237619dd5dfc2a5 to your computer and use it in GitHub Desktop.
Save curtiscook/65d6caf95b5834b82237619dd5dfc2a5 to your computer and use it in GitHub Desktop.
Python 3 - Singleton Access Pattern
import os
from typing import Any, Dict
class Singleton(type):
_instances: Dict[Any, Any] = {}
def __call__(cls, *args: Any, **kwargs: Any) -> Any:
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# test file
import pytest
pytestmark = pytest.mark.asyncio
class ClassA:
def __init__(self) -> None:
self.rand = os.urandom(10)
class ClassB(ClassA, metaclass=Singleton):
pass
async def test_singleton() -> None:
instance_a1 = ClassA()
instance_a2 = ClassA()
instance_b1 = ClassB()
instance_b2 = ClassB()
assert instance_a1 != instance_a2
assert instance_a1 != instance_b1
assert instance_b2 is instance_b1
assert instance_b1.rand == instance_b2.rand
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment