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, 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