A singleton class representing the backward engine. This class ensures that only one instance of the backward engine is created and provides methods to set and get the engine.
| 2 | from typing import Union |
| 3 | |
| 4 | class SingletonBackwardEngine: |
| 5 | """ |
| 6 | A singleton class representing the backward engine. |
| 7 | |
| 8 | This class ensures that only one instance of the backward engine is created and provides methods to set and get the engine.""" |
| 9 | |
| 10 | _instance = None |
| 11 | |
| 12 | def __new__(cls): |
| 13 | if not cls._instance: |
| 14 | cls._instance = super(SingletonBackwardEngine, cls).__new__(cls) |
| 15 | return cls._instance |
| 16 | |
| 17 | def __init__(self): |
| 18 | if not hasattr(self, 'engine'): |
| 19 | self.engine: EngineLM = None |
| 20 | |
| 21 | def set_engine(self, engine: EngineLM, override: bool = False): |
| 22 | """ |
| 23 | Sets the backward engine. |
| 24 | |
| 25 | :param engine: The backward engine to set. |
| 26 | :type engine: EngineLM |
| 27 | :param override: Whether to override the existing engine if it is already set. Defaults to False. |
| 28 | :type override: bool |
| 29 | :raises Exception: If the engine is already set and override is False. |
| 30 | :return: None |
| 31 | """ |
| 32 | if ((self.engine is not None) and (not override)): |
| 33 | raise Exception("Engine already set. Use override=True to override cautiously.") |
| 34 | self.engine = engine |
| 35 | |
| 36 | def get_engine(self): |
| 37 | """ |
| 38 | Returns the backward engine. |
| 39 | |
| 40 | :return: The backward engine. |
| 41 | :rtype: EngineLM |
| 42 | """ |
| 43 | return self.engine |
| 44 | |
| 45 | def set_backward_engine(engine: Union[EngineLM, str], override: bool = False, **kwargs): |
| 46 | singleton_backward_engine = SingletonBackwardEngine() |
no outgoing calls
no test coverage detected