Skip to content

Instantly share code, notes, and snippets.

@Congee
Created September 22, 2022 19:46
Show Gist options
  • Save Congee/e201366a022c5f28e70fbc4a40c833fa to your computer and use it in GitHub Desktop.
Save Congee/e201366a022c5f28e70fbc4a40c833fa to your computer and use it in GitHub Desktop.
Python Singleton
from typing import Any, Callable, ParamSpec, Type, TypeVar
T = TypeVar('T')
P = ParamSpec('P')
def singleton(cls: Type[T]) -> Callable[P, T]:
"""
Example:
>>> @singleton
... class C: ...
>>> assert C() is C()
>>> # import types; assert isinstance(C, types.FunctionTYpe)
>>> import inspect; assert inspect.isfunction(C) # bad
"""
instances: dict[Type[T], T] = {}
def getinstance(*args: P.args, **kwargs: P.kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return getinstance
class Singleton(type):
"""
Example:
>>> class S(metaclass=Singleton): ...
>>> assert S() is S()
"""
_instances: dict[type, Any] = {}
def __call__(cls, *args: Any, **kwargs: Any):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment