From c57fcbfbc0b30d7018d3c847888bc5c7987d4cef Mon Sep 17 00:00:00 2001 From: Eran Date: Tue, 17 Dec 2024 22:23:16 -0500 Subject: [PATCH] core is a singleton --- process_bigraph/__init__.py | 4 +++- process_bigraph/composite.py | 25 +++++++++++++++++-------- process_bigraph/tests.py | 7 +++++++ 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/process_bigraph/__init__.py b/process_bigraph/__init__.py index a3c439b..9767f91 100644 --- a/process_bigraph/__init__.py +++ b/process_bigraph/__init__.py @@ -3,9 +3,11 @@ from process_bigraph.processes import register_processes from process_bigraph.composite import Process, Step, Composite, ProcessTypes, interval_time_precision - pretty = pprint.PrettyPrinter(indent=2) +# make the singleton instance of the ProcessTypes class +core = ProcessTypes() + def pp(x): """Print ``x`` in a pretty format.""" diff --git a/process_bigraph/composite.py b/process_bigraph/composite.py index fe496e6..5f4d931 100644 --- a/process_bigraph/composite.py +++ b/process_bigraph/composite.py @@ -251,18 +251,27 @@ class ProcessTypes(TypeSystem): It maintains a registry of process types and provides methods to register new process types, protocols, and emitters. """ + _instance = None # Class-level private variable for the singleton instance - def __init__(self): - super().__init__() - self.process_registry = Registry() - self.protocol_registry = Registry() + def __new__(cls, *args, **kwargs): + if cls._instance is None: + cls._instance = super(ProcessTypes, cls).__new__(cls) + # Initialize the instance + cls._instance._is_initialized = False + return cls._instance - self.register_types(PROCESS_TYPES) - self.register_protocols(BASE_PROTOCOLS) - self.register_processes(BASE_EMITTERS) + def __init__(self): + if not self._is_initialized: # Prevent re-initialization + super().__init__() + self.process_registry = Registry() + self.protocol_registry = Registry() - self.register_process('composite', Composite) + self.register_types(PROCESS_TYPES) + self.register_protocols(BASE_PROTOCOLS) + self.register_processes(BASE_EMITTERS) + self.register_process('composite', Composite) + self._is_initialized = True def register_protocols(self, protocols): """Register protocols with the core""" diff --git a/process_bigraph/tests.py b/process_bigraph/tests.py index c5b44eb..0486805 100644 --- a/process_bigraph/tests.py +++ b/process_bigraph/tests.py @@ -731,6 +731,13 @@ def test_stochastic_deterministic_composite(core): pass +def test_singleton_core(): + from process_bigraph import core + from process_bigraph import ProcessTypes + core2 = ProcessTypes() # This should point to the singleton instance + assert core is core2, "ProcessTypes is not behaving like a singleton." + + if __name__ == '__main__': core = ProcessTypes() core = register_types(core)