Values From Type

fejao_config_parser.src.values.values_from_type

Convert parsed string values into typed configuration values.

This module provides the ValuesFromType helper class that converts raw configuration values into target Python types defined by the configuration schema. It is used by environment and terminal parsers to normalize text-based inputs into typed values.

ValuesFromType

Convert a raw configuration value into a specified type.

ValuesFromType supports conversion for string, boolean, integer, float, list, and dictionary types. It raises a descriptive ValueError when a raw value cannot be converted or when the requested type is unsupported.

Attributes:
  • source_name (str) –

    Human-readable parser source used in error messages.

Source code in fejao_config_parser/src/values/values_from_type.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
class ValuesFromType:
    """Convert a raw configuration value into a specified type.

    `ValuesFromType` supports conversion for string, boolean, integer, float,
    list, and dictionary types. It raises a descriptive `ValueError` when a raw
    value cannot be converted or when the requested type is unsupported.

    Attributes:
        source_name (str): Human-readable parser source used in error messages.
    """

    def __init__(self, source_name: str) -> None:
        """Initialize the converter with the parser source name.

        Args:
            source_name (str): Name of the source producing values, such as \
            "environment" or "terminal".
        """
        self.source_name = source_name

    def __get_error_msg(self, value_type, value_found, err_desc: str = None) -> str:
        """
        Generate a descriptive error message for type conversion failures.

        Args:
            value_type (str): The target type that was attempted for conversion.
            value_found (str | int | float | bool | list | dict): The raw value that failed to convert.
            err_desc (str, optional): Additional error description to include in the message.

        Returns:
            str: A formatted error message string.
        """
        return (f"\n\nError parsing the '{self.source_name}' variable for the type "
                f"'{value_type}'. The value found is: '{value_found}'. "
                f"{err_desc}")

    def __get_from_bool(self, value_found: str | bool) -> bool:
        """
        Convert a raw value to a boolean type.

        Args:
            value_found (str | bool): The raw value to convert, which can be a \
            string representation of a boolean or an actual boolean.

        Returns:
            bool: The converted boolean value.
        """
        if isinstance(value_found, bool):
            return value_found

        list_true = [
            "True",
            "true",
            "TRUE",
            "Yes",
            "yes",
            "YES",
            "On",
            "on",
            "ON",
        ]

        list_false = [
            "False",
            "false",
            "FALSE",
            "No",
            "no",
            "NO",
            "Off",
            "off",
            "OFF",
        ]

        if value_found in list_true:
            return True

        if value_found in list_false:
            return False

        raise ValueError(
            self.__get_error_msg(
                value_type="boolean",
                value_found=value_found,
                err_desc=(
                    f"The accepted values for boolean types are: '{list_true}' and '{list_false}'. "
                    "Please refer to the documentation for more details.\n")
            )
        )

    def __get_from_int(self, value_found: str | int) -> int:
        """Convert a raw value to an integer type.

        Args:
            value_found (str | int): The raw value to convert, which can be a \
            string representation of an integer or an actual integer.

        Returns:
            int: The converted integer value.
        """
        if isinstance(value_found, int):
            return value_found

        try:
            return int(value_found)
        except ValueError:
            print(
                self.__get_error_msg(
                    value_type="int",
                    value_found=value_found,
                    err_desc=(
                        "The value cannot be converted to an integer. "
                        "Please refer to the documentation for more details.\n")
                )
            )
            raise

    def __get_from_float(self, value_found: str | float) -> float:
        """
        Convert a raw value to a float type.

        Args:
            value_found (str | float): The raw value to convert, which can be a \
            string representation of a float or an actual float.

        Returns:
            float: The converted float value.
        """
        if isinstance(value_found, float):
            return value_found

        try:
            return float(value_found)
        except ValueError:
            print(
                self.__get_error_msg(
                    value_type="float",
                    value_found=value_found,
                    err_desc=(
                        "The value cannot be converted to an float. "
                        "Please refer to the documentation for more details.\n")
                )
            )
            raise

    def __get_from_list(self, value_found: str | list) -> list:
        """
        Convert a raw value to a list type.

        Args:
            value_found (str | list): The raw value to convert, which can be a \
            string representation of a list or an actual list.

        Returns:
            list: The converted list value.
        """
        if isinstance(value_found, list):
            return value_found

        try:
            value_found = value_found.strip()

            # First try normal Python parsing
            try:
                return literal_eval(value_found)
            except Exception:
                pass

            # Handle custom format like: [a,b,c]
            if value_found.startswith("[") and value_found.endswith("]"):
                inner = value_found[1:-1].strip()
                result = []
                for item in inner.split(","):
                    item = item.strip()
                    # Try converting each item individually
                    try:
                        parsed_item = literal_eval(item)
                    except Exception:
                        parsed_item = item

                    result.append(parsed_item)

                return result

            raise ValueError("Invalid list format")

        except Exception as e:
            print(
                self.__get_error_msg(
                    value_type="list",
                    value_found=value_found,
                    err_desc=(
                        f"The value cannot be converted to a list. "
                        f"The error found was: {e}.\n"
                    )
                )
            )
            raise

    def __get_from_dict(self, value_found: str | dict) -> dict:
        """
        Convert a raw value to a dictionary type.

        Args:
            value_found (str | dict): The raw value to convert, which can be a \
            string representation of a dictionary or an actual dictionary.

        Returns:
            dict: The converted dictionary value.
        """
        if isinstance(value_found, dict):
            return value_found

        try:
            return literal_eval(value_found)
        except Exception as e:
            print(
                self.__get_error_msg(
                    value_type="dict",
                    value_found=value_found,
                    err_desc=(
                        f"The value cannot be converted to a dictionary. The error found was: {e}."
                        "Please refer to the documentation for more details.\n")
                )
            )
            raise

    def get_value(
        self,
        value_type: str,
        value_found: str | int | float | bool | list | dict,
    ) -> str | int | float | bool | list | dict:
        """Convert a raw value to the desired configuration type.

        Args:
            value_type (str): Desired target type name.
            value_found (str | int | float | bool | list | dict): Raw value to convert.

        Returns:
            str | int | float | bool | list | dict: The converted value.

        Raises:
            ValueError: If the value cannot be converted to the requested type, \
            or if the requested type is unsupported.
        """
        ### STRING
        if value_type.lower() == "string" or value_type.lower() == "str":
            return str(value_found)

        ### BOOL
        if value_type.lower() == "bool" or value_type.lower() == "boolean":
            return self.__get_from_bool(value_found=value_found)

        ### INT
        if value_type.lower() == "int" or value_type.lower() == "integer":
            return self.__get_from_int(value_found=value_found)

        ### FLOAT
        if value_type.lower() == "float" or value_type.lower() == "double":
            return self.__get_from_float(value_found=value_found)

        ### LIST
        if value_type.lower() == "list" or value_type.lower() == "lst":
            return self.__get_from_list(value_found=value_found)

        ### DICT
        if value_type.lower() == "dict" or value_type.lower() == "dictionary":
            return self.__get_from_dict(value_found=value_found)

        ### NOT SUPPORTED
        raise ValueError(
            f"\n\nError parsing the '{self.source_name}' variable for the type "
            f"'{value_type}'. The type is not supported. The accepted types are: "
            f"{DEFAULT_ACCEPTED_KEY_TYPES}. Please refer to the documentation "
            "for more details.\n"
        )
Methods:
__get_error_msg
__get_error_msg(value_type, value_found, err_desc: str = None) -> str

Generate a descriptive error message for type conversion failures.

Parameters:
  • value_type (str) –

    The target type that was attempted for conversion.

  • value_found (str | int | float | bool | list | dict) –

    The raw value that failed to convert.

  • err_desc (str, default: None ) –

    Additional error description to include in the message.

Returns:
  • str( str ) –

    A formatted error message string.

Source code in fejao_config_parser/src/values/values_from_type.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def __get_error_msg(self, value_type, value_found, err_desc: str = None) -> str:
    """
    Generate a descriptive error message for type conversion failures.

    Args:
        value_type (str): The target type that was attempted for conversion.
        value_found (str | int | float | bool | list | dict): The raw value that failed to convert.
        err_desc (str, optional): Additional error description to include in the message.

    Returns:
        str: A formatted error message string.
    """
    return (f"\n\nError parsing the '{self.source_name}' variable for the type "
            f"'{value_type}'. The value found is: '{value_found}'. "
            f"{err_desc}")
__get_from_bool
__get_from_bool(value_found: str | bool) -> bool

Convert a raw value to a boolean type.

Parameters:
  • value_found (str | bool) –

    The raw value to convert, which can be a string representation of a boolean or an actual boolean.

Returns:
  • bool( bool ) –

    The converted boolean value.

Source code in fejao_config_parser/src/values/values_from_type.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def __get_from_bool(self, value_found: str | bool) -> bool:
    """
    Convert a raw value to a boolean type.

    Args:
        value_found (str | bool): The raw value to convert, which can be a \
        string representation of a boolean or an actual boolean.

    Returns:
        bool: The converted boolean value.
    """
    if isinstance(value_found, bool):
        return value_found

    list_true = [
        "True",
        "true",
        "TRUE",
        "Yes",
        "yes",
        "YES",
        "On",
        "on",
        "ON",
    ]

    list_false = [
        "False",
        "false",
        "FALSE",
        "No",
        "no",
        "NO",
        "Off",
        "off",
        "OFF",
    ]

    if value_found in list_true:
        return True

    if value_found in list_false:
        return False

    raise ValueError(
        self.__get_error_msg(
            value_type="boolean",
            value_found=value_found,
            err_desc=(
                f"The accepted values for boolean types are: '{list_true}' and '{list_false}'. "
                "Please refer to the documentation for more details.\n")
        )
    )
__get_from_dict
__get_from_dict(value_found: str | dict) -> dict

Convert a raw value to a dictionary type.

Parameters:
  • value_found (str | dict) –

    The raw value to convert, which can be a string representation of a dictionary or an actual dictionary.

Returns:
  • dict( dict ) –

    The converted dictionary value.

Source code in fejao_config_parser/src/values/values_from_type.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
def __get_from_dict(self, value_found: str | dict) -> dict:
    """
    Convert a raw value to a dictionary type.

    Args:
        value_found (str | dict): The raw value to convert, which can be a \
        string representation of a dictionary or an actual dictionary.

    Returns:
        dict: The converted dictionary value.
    """
    if isinstance(value_found, dict):
        return value_found

    try:
        return literal_eval(value_found)
    except Exception as e:
        print(
            self.__get_error_msg(
                value_type="dict",
                value_found=value_found,
                err_desc=(
                    f"The value cannot be converted to a dictionary. The error found was: {e}."
                    "Please refer to the documentation for more details.\n")
            )
        )
        raise
__get_from_float
__get_from_float(value_found: str | float) -> float

Convert a raw value to a float type.

Parameters:
  • value_found (str | float) –

    The raw value to convert, which can be a string representation of a float or an actual float.

Returns:
  • float( float ) –

    The converted float value.

Source code in fejao_config_parser/src/values/values_from_type.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def __get_from_float(self, value_found: str | float) -> float:
    """
    Convert a raw value to a float type.

    Args:
        value_found (str | float): The raw value to convert, which can be a \
        string representation of a float or an actual float.

    Returns:
        float: The converted float value.
    """
    if isinstance(value_found, float):
        return value_found

    try:
        return float(value_found)
    except ValueError:
        print(
            self.__get_error_msg(
                value_type="float",
                value_found=value_found,
                err_desc=(
                    "The value cannot be converted to an float. "
                    "Please refer to the documentation for more details.\n")
            )
        )
        raise
__get_from_int
__get_from_int(value_found: str | int) -> int

Convert a raw value to an integer type.

Parameters:
  • value_found (str | int) –

    The raw value to convert, which can be a string representation of an integer or an actual integer.

Returns:
  • int( int ) –

    The converted integer value.

Source code in fejao_config_parser/src/values/values_from_type.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def __get_from_int(self, value_found: str | int) -> int:
    """Convert a raw value to an integer type.

    Args:
        value_found (str | int): The raw value to convert, which can be a \
        string representation of an integer or an actual integer.

    Returns:
        int: The converted integer value.
    """
    if isinstance(value_found, int):
        return value_found

    try:
        return int(value_found)
    except ValueError:
        print(
            self.__get_error_msg(
                value_type="int",
                value_found=value_found,
                err_desc=(
                    "The value cannot be converted to an integer. "
                    "Please refer to the documentation for more details.\n")
            )
        )
        raise
__get_from_list
__get_from_list(value_found: str | list) -> list

Convert a raw value to a list type.

Parameters:
  • value_found (str | list) –

    The raw value to convert, which can be a string representation of a list or an actual list.

Returns:
  • list( list ) –

    The converted list value.

Source code in fejao_config_parser/src/values/values_from_type.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def __get_from_list(self, value_found: str | list) -> list:
    """
    Convert a raw value to a list type.

    Args:
        value_found (str | list): The raw value to convert, which can be a \
        string representation of a list or an actual list.

    Returns:
        list: The converted list value.
    """
    if isinstance(value_found, list):
        return value_found

    try:
        value_found = value_found.strip()

        # First try normal Python parsing
        try:
            return literal_eval(value_found)
        except Exception:
            pass

        # Handle custom format like: [a,b,c]
        if value_found.startswith("[") and value_found.endswith("]"):
            inner = value_found[1:-1].strip()
            result = []
            for item in inner.split(","):
                item = item.strip()
                # Try converting each item individually
                try:
                    parsed_item = literal_eval(item)
                except Exception:
                    parsed_item = item

                result.append(parsed_item)

            return result

        raise ValueError("Invalid list format")

    except Exception as e:
        print(
            self.__get_error_msg(
                value_type="list",
                value_found=value_found,
                err_desc=(
                    f"The value cannot be converted to a list. "
                    f"The error found was: {e}.\n"
                )
            )
        )
        raise
__init__
__init__(source_name: str) -> None

Initialize the converter with the parser source name.

Parameters:
  • source_name (str) –

    Name of the source producing values, such as "environment" or "terminal".

Source code in fejao_config_parser/src/values/values_from_type.py
27
28
29
30
31
32
33
34
def __init__(self, source_name: str) -> None:
    """Initialize the converter with the parser source name.

    Args:
        source_name (str): Name of the source producing values, such as \
        "environment" or "terminal".
    """
    self.source_name = source_name
get_value
get_value(value_type: str, value_found: str | int | float | bool | list | dict) -> str | int | float | bool | list | dict

Convert a raw value to the desired configuration type.

Parameters:
  • value_type (str) –

    Desired target type name.

  • value_found (str | int | float | bool | list | dict) –

    Raw value to convert.

Returns:
  • str | int | float | bool | list | dict –

    str | int | float | bool | list | dict: The converted value.

Raises:
  • ValueError –

    If the value cannot be converted to the requested type, or if the requested type is unsupported.

Source code in fejao_config_parser/src/values/values_from_type.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def get_value(
    self,
    value_type: str,
    value_found: str | int | float | bool | list | dict,
) -> str | int | float | bool | list | dict:
    """Convert a raw value to the desired configuration type.

    Args:
        value_type (str): Desired target type name.
        value_found (str | int | float | bool | list | dict): Raw value to convert.

    Returns:
        str | int | float | bool | list | dict: The converted value.

    Raises:
        ValueError: If the value cannot be converted to the requested type, \
        or if the requested type is unsupported.
    """
    ### STRING
    if value_type.lower() == "string" or value_type.lower() == "str":
        return str(value_found)

    ### BOOL
    if value_type.lower() == "bool" or value_type.lower() == "boolean":
        return self.__get_from_bool(value_found=value_found)

    ### INT
    if value_type.lower() == "int" or value_type.lower() == "integer":
        return self.__get_from_int(value_found=value_found)

    ### FLOAT
    if value_type.lower() == "float" or value_type.lower() == "double":
        return self.__get_from_float(value_found=value_found)

    ### LIST
    if value_type.lower() == "list" or value_type.lower() == "lst":
        return self.__get_from_list(value_found=value_found)

    ### DICT
    if value_type.lower() == "dict" or value_type.lower() == "dictionary":
        return self.__get_from_dict(value_found=value_found)

    ### NOT SUPPORTED
    raise ValueError(
        f"\n\nError parsing the '{self.source_name}' variable for the type "
        f"'{value_type}'. The type is not supported. The accepted types are: "
        f"{DEFAULT_ACCEPTED_KEY_TYPES}. Please refer to the documentation "
        "for more details.\n"
    )