Fixed get_value
Some checks failed
Build on push / prepare (push) Has been cancelled
Build on push / build-api (push) Has been cancelled
Build on push / build-redirector (push) Has been cancelled
Build on push / build-web (push) Has been cancelled

This commit is contained in:
Sven Heidemann 2025-02-16 21:35:57 +01:00
parent 254b03d601
commit fafa588880

View File

@ -1,15 +1,14 @@
import ast from typing import Type, Optional
from typing import Type, Optional, Any
from core.typing import T from core.typing import T
def get_value( def get_value(
source: dict, source: dict,
key: str, key: str,
cast_type: Type[T], cast_type: Type[T],
default: Optional[T] = None, default: Optional[T] = None,
list_delimiter: str = ",", list_delimiter: str = ",",
) -> Optional[T]: ) -> Optional[T]:
""" """
Get value from source dictionary and cast it to a specified type. Get value from source dictionary and cast it to a specified type.
@ -22,33 +21,33 @@ def get_value(
:rtype: Optional[T] :rtype: Optional[T]
""" """
if key in source: if key not in source:
value = source[key] return default
if isinstance(
value = source[key]
if isinstance(
value, value,
cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__, cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__,
): ):
return value return value
try: try:
if cast_type == bool: if cast_type == bool:
return value.lower() in ["true", "1"] return value.lower() in ["true", "1"]
if ( if (
cast_type cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__
if not hasattr(cast_type, "__origin__") ) == list:
else cast_type.__origin__ if not (value.startswith("[") and value.endswith("]")) and list_delimiter not in value:
) == list: raise ValueError("List values must be enclosed in square brackets or use a delimiter.")
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
]
return cast_type(value) if value.startswith("[") and value.endswith("]"):
except (ValueError, TypeError): value = value[1:-1]
return default
else: 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 return default