diff --git a/api/src/core/get_value.py b/api/src/core/get_value.py index aff4788..6acec5a 100644 --- a/api/src/core/get_value.py +++ b/api/src/core/get_value.py @@ -1,15 +1,14 @@ -import ast -from typing import Type, Optional, Any +from typing import Type, Optional from core.typing import T def get_value( - source: dict, - key: str, - cast_type: Type[T], - default: Optional[T] = None, - list_delimiter: str = ",", + source: dict, + key: str, + cast_type: Type[T], + default: Optional[T] = None, + list_delimiter: str = ",", ) -> Optional[T]: """ Get value from source dictionary and cast it to a specified type. @@ -22,33 +21,33 @@ def get_value( :rtype: Optional[T] """ - if key in source: - value = source[key] - if isinstance( + if key not in source: + return default + + value = source[key] + if isinstance( value, cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__, - ): - return value + ): + return value - try: - if cast_type == bool: - return value.lower() in ["true", "1"] + try: + if cast_type == bool: + return value.lower() in ["true", "1"] - if ( - cast_type - if not hasattr(cast_type, "__origin__") - else cast_type.__origin__ - ) == list: - subtype = ( - cast_type.__args__[0] if hasattr(cast_type, "__args__") else None - ) - value = value.split(list_delimiter) - return [ - subtype(item) if subtype is not None else item for item in value - ] + if ( + cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__ + ) == list: + if not (value.startswith("[") and value.endswith("]")) and list_delimiter not in value: + raise ValueError("List values must be enclosed in square brackets or use a delimiter.") - return cast_type(value) - except (ValueError, TypeError): - return default - else: + if value.startswith("[") and value.endswith("]"): + value = value[1:-1] + + value = value.split(list_delimiter) + subtype = cast_type.__args__[0] if hasattr(cast_type, "__args__") else None + return [subtype(item) if subtype is not None else item for item in value] + + return cast_type(value) + except (ValueError, TypeError): return default