mirror of
https://github.com/agentscope-ai/ReMe.git
synced 2026-09-17 23:51:19 +00:00
Some checks are pending
Pre-commit / run (ubuntu-latest) (push) Waiting to run
- Introduce BaseAsTokenCounter and EstimatedAsTokenCounter for token estimation - Add AsMsgStat and AsBlockStat schema for message statistics tracking - Implement FileIO class with read/write/append/edit operations - Create file utility functions for safe async file reading and truncation - Add MemorySearch component for semantic search in memory files - Register new component types in ComponentEnum and update imports - Add constants for default host, port, and truncation limits - Create BaseService abstract base class for service implementations - Implement BaseStep with component accessors and lifecycle management - Add proper __all__ exports for all new modules and components
43 lines
1.2 KiB
Python
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
|