Coverage for source/utils/base_from_string_converter.py: 89%
9 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-30 15:13 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-05-30 15:13 +0000
1# utils/base_from_string_converter.py
3from typing import Any
4import logging
6class BaseFromStringConverter():
7 """
8 Base class for string-to-object conversion functionality.
10 This class provides a framework for converting string identifiers into actual
11 object instances. Subclasses implement specific conversion logic by defining
12 value maps that link string identifiers to their corresponding classes or values.
13 All converter implementations should inherit from this class and override
14 the __init__ method.
15 """
17 def __init__(self, **kwargs: dict[str, Any]) -> None:
18 """
19 Initializes the converter with optional parameters.
21 Parameters:
22 **kwargs (dict[str, Any]): Optional parameters that will be passed to
23 the constructor of the converted objects.
25 Raises:
26 NotImplementedError: If the method is not implemented by a subclass.
27 """
29 raise NotImplementedError("Subclasses must implement this method")
31 def convert_from_string(self, string_value: str) -> Any:
32 """
33 Converts a string identifier to its corresponding object.
35 Uses the _value_map dictionary from the subclass to convert the string
36 to an actual object instance by looking up the corresponding class and
37 instantiating it with the parameters provided at initialization.
39 Parameters:
40 string_value (str): String identifier to convert.
42 Returns:
43 Any: An instance of the class corresponding to the string identifier.
44 Returns None if conversion fails.
45 """
47 converted_value = self._value_map.get(string_value, None)
48 if converted_value is None:
49 logging.warning(f'Did not managed to convert {string_value}, returning None.')
51 return converted_value(**self._kwargs)