From 7ae9138354c65d5e90bcde6947945d0a57015235 Mon Sep 17 00:00:00 2001 From: ff137 Date: Thu, 28 Nov 2024 12:53:25 +0200 Subject: [PATCH] :zap: Add class caching to DeferLoad Resolves #3360 Signed-off-by: ff137 --- acapy_agent/utils/classloader.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/acapy_agent/utils/classloader.py b/acapy_agent/utils/classloader.py index 29fd81bc4d..09d4799aea 100644 --- a/acapy_agent/utils/classloader.py +++ b/acapy_agent/utils/classloader.py @@ -181,18 +181,21 @@ def scan_subpackages(cls, package: str) -> Sequence[str]: class DeferLoad: """Helper to defer loading of a class definition.""" + _class_cache = {} # Shared cache for resolved classes + def __init__(self, cls_path: str): """Initialize the `DeferLoad` instance with a qualified class path.""" self._cls_path = cls_path - self._inst = None def __call__(self, *args, **kwargs): """Magic method to call the `DeferLoad` as a function.""" - return (self.resolved)(*args, **kwargs) + return self.resolved(*args, **kwargs) @property def resolved(self): """Accessor for the resolved class instance.""" - if not self._inst: - self._inst = ClassLoader.load_class(self._cls_path) - return self._inst + if self._cls_path not in DeferLoad._class_cache: + DeferLoad._class_cache[self._cls_path] = ClassLoader.load_class( + self._cls_path + ) + return DeferLoad._class_cache[self._cls_path]