Created
December 8, 2022 03:02
-
-
Save curtiscook/65d6caf95b5834b82237619dd5dfc2a5 to your computer and use it in GitHub Desktop.
Python 3 - Singleton Access Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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