From c00c623400700f20dbdeba4dab293b417bd10b75 Mon Sep 17 00:00:00 2001 From: DIGVIJAY <144053736+digvijay-y@users.noreply.github.com> Date: Sun, 24 Nov 2024 00:35:07 +0530 Subject: [PATCH] Update settings.py Thread-Safe Singleton: Uses a lock to ensure only one instance of Settings is created, even when accessed in a multithreaded environment. Extendability: Additional configuration parameters can easily be added as fields in the Settings dataclass. Immutability: The frozen=True parameter ensures the settings remain immutable after initialization. --- src/aleph/settings.py | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/aleph/settings.py b/src/aleph/settings.py index a24a8ea16..bf868e34d 100644 --- a/src/aleph/settings.py +++ b/src/aleph/settings.py @@ -1,10 +1,27 @@ -from dataclasses import dataclass +from dataclasses import dataclass, field +from threading import Lock -@dataclass(frozen=True, eq=True) +@dataclass(frozen=True) class Settings: - use_executors: bool = True + """Immutable configuration settings.""" + use_executors: bool = field(default=True) + _instance = None # Private class-level variable for Singleton instance + _lock = Lock() # Lock to ensure thread-safe initialization -# Singleton -settings = Settings() + @classmethod + def instance(cls): + """ + Get the Singleton instance of the Settings class. + Ensures only one instance is created even in multithreaded environments. + """ + if cls._instance is None: + with cls._lock: # Double-checked locking + if cls._instance is None: + cls._instance = cls() # Initialize the Singleton instance + return cls._instance + + +# Access the Singleton instance +settings = Settings.instance()