27 lines
584 B
Python
27 lines
584 B
Python
import functools
|
|
|
|
from typing import Any, MutableMapping, Type
|
|
|
|
|
|
class Singleton(type):
|
|
_instances: MutableMapping[Type[Any], Any] = {}
|
|
|
|
def __call__(cls, *args, **kwargs):
|
|
if cls not in cls._instances:
|
|
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
|
|
|
return cls._instances[cls]
|
|
|
|
|
|
def memoized_property(fgetter):
|
|
stored = []
|
|
|
|
@functools.wraps(fgetter)
|
|
def wrapped(self):
|
|
nonlocal stored
|
|
if not stored:
|
|
stored.append(fgetter(self))
|
|
return stored[0]
|
|
|
|
return property(wrapped)
|