-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #28 from glrs/feature/core
Introduce `SingletonMeta` metaclass and refactor singleton decorator …
- Loading branch information
Showing
1 changed file
with
27 additions
and
14 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,38 @@ | ||
from typing import Any, Callable, Dict, Type, TypeVar | ||
from typing import Any, Dict, Type | ||
|
||
T = TypeVar("T") | ||
|
||
class SingletonMeta(type): | ||
""" | ||
A metaclass that creates a singleton instance of a class. | ||
""" | ||
|
||
_instances: Dict[type, Any] = {} | ||
|
||
def singleton(cls: Type[T]) -> Callable[..., T]: | ||
"""Decorator to make a class a singleton. | ||
def __call__(cls, *args: Any, **kwargs: Any) -> Any: | ||
if cls not in cls._instances: | ||
cls._instances[cls] = super().__call__(*args, **kwargs) | ||
return cls._instances[cls] | ||
|
||
Ensures that only one instance of the class is created. Subsequent | ||
calls to the class will return the same instance. | ||
|
||
def singleton(cls: Type[Any]) -> Type[Any]: | ||
""" | ||
Decorator to make a class a singleton by setting its metaclass to SingletonMeta. | ||
Args: | ||
cls (Type[T]): The class to be decorated. | ||
cls (Type[Any]): The class to be decorated. | ||
Returns: | ||
Callable[..., T]: A function that returns the singleton instance of the class. | ||
Type[Any]: The singleton class with SingletonMeta as its metaclass. | ||
""" | ||
instances: Dict[Type[T], T] = {} | ||
|
||
def get_instance(*args: Any, **kwargs: Any) -> T: | ||
if cls not in instances: | ||
instances[cls] = cls(*args, **kwargs) | ||
return instances[cls] | ||
# Create a new class with SingletonMeta as its metaclass | ||
class SingletonClass(cls, metaclass=SingletonMeta): | ||
pass | ||
|
||
# Preserve class metadata | ||
SingletonClass.__name__ = cls.__name__ | ||
SingletonClass.__doc__ = cls.__doc__ | ||
SingletonClass.__module__ = cls.__module__ | ||
SingletonClass.__annotations__ = getattr(cls, "__annotations__", {}) | ||
|
||
return get_instance | ||
return SingletonClass |