ReMe/reme_cli/utils/singleton.py
jinli.yl 4b5fb37b6a
Some checks are pending
Pre-commit / run (ubuntu-latest) (push) Waiting to run
feat(core): add core components and architecture for ReMe CLI
- Implement BaseComponent with async lifecycle and context management
- Add ApplicationContext for managing component initialization and registry
- Create Application class for orchestrating job execution and lifecycle
- Add AS LLM components with OpenAI chat model wrapper
- Implement AS LLM formatter components with OpenAI formatter
- Add client implementations including base, HTTP and ReMe clients
- Create embedding model base class with caching and batching support
- Implement file store base class with vector and full-text search
- Add file watcher components for monitoring file system changes
- Create job components for executing workflows
- Implement service components for exposing jobs via different protocols
- Add configuration schema with ApplicationConfig and ComponentConfig
- Include utility modules for case conversion, chunking, logging and similarity
- Register component types and create component registry system
2026-04-13 23:51:59 +08:00

43 lines
1.2 KiB
Python

"""Singleton pattern implementation using a class decorator.
Provides a thread-safe singleton decorator that ensures only one instance
of a decorated class exists throughout the application lifecycle.
"""
import threading
from typing import Any, Callable, TypeVar
T = TypeVar("T")
def singleton(cls: type[T]) -> Callable[..., T]:
"""A class decorator that ensures only one instance of a class exists.
Thread-safe implementation using a lock to prevent race conditions
during instance creation.
Args:
cls: The class to decorate with singleton behavior.
Returns:
A wrapper function that returns the single instance.
"""
_instance: dict[type[T], T] = {}
_lock = threading.Lock()
def _singleton(*args: Any, **kwargs: Any) -> T:
"""Return the existing instance or create a new one if it doesn't exist.
Args:
*args: Positional arguments passed to the class constructor.
**kwargs: Keyword arguments passed to the class constructor.
Returns:
The single instance of the decorated class.
"""
with _lock:
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return _singleton