# Copyright 2026 European Union
# Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
# SPDX-License-Identifier: EUPL-1.2
"""
Singleton pattern implementation for RadioViz application.
This module provides a decorator for implementing the singleton pattern,
ensuring that only one instance of a class is ever created.
"""
from __future__ import annotations
from typing import Any, Generic, Type, TypeVar
T = TypeVar('T')
[docs]
class _SingletonWrapper(Generic[T]):
"""
Wrapper class that implements the singleton pattern logic.
This internal class handles the creation and management of singleton instances
for decorated classes. It ensures that only one instance is created and
returned on subsequent calls.
"""
def __init__(self, cls: Type[T]) -> None:
"""
Initialize the singleton wrapper.
:param cls: The class to be wrapped as a singleton
:type cls: type
"""
self.__wrapped__: Type[T] = cls
self._instance: T | None = None
def __call__(self, *args: Any, **kwargs: Any) -> T:
"""
Return a single instance of the decorated class.
If no instance exists yet, creates a new one with the provided arguments.
Otherwise, returns the existing instance.
:param args: Positional arguments for the class constructor
:param kwargs: Keyword arguments for the class constructor
:return: Single instance of the wrapped class
:rtype: object
"""
if self._instance is None:
self._instance = self.__wrapped__(*args, **kwargs)
return self._instance
[docs]
def singleton(cls: Type[T]) -> _SingletonWrapper[T]:
"""
Decorator to make a class a singleton.
This function takes a class and returns a singleton wrapper that ensures
only one instance of the class will ever be created.
:param cls: The class to be converted into a singleton
:type cls: type
:return: A singleton wrapper for the given class
:rtype: _SingletonWrapper
"""
return _SingletonWrapper(cls)