From 08b1aa76311c6e328f59cad831ff48e416cb45e8 Mon Sep 17 00:00:00 2001 From: Bhavit Sharma Date: Sat, 8 Jul 2023 00:28:58 +0530 Subject: [PATCH] Fix --- automata/core/base/patterns/singleton.py | 19 ++++++++++++++++++- automata/singletons/py_module_loader.py | 9 +++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/automata/core/base/patterns/singleton.py b/automata/core/base/patterns/singleton.py index b035999c..790bd2f1 100644 --- a/automata/core/base/patterns/singleton.py +++ b/automata/core/base/patterns/singleton.py @@ -1,5 +1,5 @@ import abc -from typing import Any, Dict +from typing import Any, Dict, List class Singleton(abc.ABCMeta, type): @@ -14,3 +14,20 @@ def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] + + +class Doubleton(abc.ABCMeta, type): + """ + Doubleton metaclass for ensuring at most two instances of a class. + """ + + _instances: Dict[str, List[Any]] = {} + + def __call__(cls, *args, **kwargs): + """Call method for the doubleton metaclass.""" + if cls not in cls._instances: + cls._instances[cls] = [] + if len(cls._instances[cls]) < 2: + instance = super(Doubleton, cls).__call__(*args, **kwargs) + cls._instances[cls].append(instance) + return cls._instances[cls][-1] # Always return the last created instance diff --git a/automata/singletons/py_module_loader.py b/automata/singletons/py_module_loader.py index d403ad49..365420f9 100644 --- a/automata/singletons/py_module_loader.py +++ b/automata/singletons/py_module_loader.py @@ -7,7 +7,7 @@ from redbaron import RedBaron -from automata.core.base.patterns.singleton import Singleton +from automata.core.base.patterns.singleton import Doubleton from automata.core.utils import get_root_fpath, get_root_py_fpath from automata.navigation.py.dotpath_map import DotPathMap @@ -23,7 +23,12 @@ class ParsingStrategy(Enum): AstType = Union[RedBaron, Module] -class PyModuleLoader(metaclass=Singleton): +# Doubleton metaclass for ensuring at most two instances of a class. +# This is used to ensure that we can have two different parsing strategies +# for the same project. +# This is just a temporary solution to avoid breaking existing code. +# Will be changed back to Singleton in the future. +class PyModuleLoader(metaclass=Doubleton): """ A Singleton with a lazy dictionary mapping dotpaths to their corresponding RedBaron FST objects. Loads and caches modules in memory as they are accessed