Skip to content

Commit 42133b6

Browse files
committed
fix(core): management one_of
1 parent 32421ae commit 42133b6

File tree

1 file changed

+16
-9
lines changed

1 file changed

+16
-9
lines changed
Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,48 @@
11
from dataclasses import dataclass
2-
from typing import Any, Dict, Generic, List, Optional, TypeVar
2+
from typing import Any, Dict, Generic, List, Optional, TypeVar, Callable
3+
4+
from scaleway_core.profile import ProfileDefaults
35

46
T = TypeVar("T")
57

68

79
@dataclass
810
class OneOfPossibility(Generic[T]):
911
param: str
10-
1112
value: Optional[T]
12-
1313
default: Optional[T] = None
14+
marshal_func: Optional[Callable[[T, ProfileDefaults], Dict[str, Any]]] = None
1415

1516

1617
def resolve_one_of(
17-
possibilities: List[OneOfPossibility[Any]], is_required: bool = False
18-
) -> Dict[str, Any]:
18+
possibilities: List[OneOfPossibility[Any]], is_required: bool = False
19+
) -> dict[str, Any | None] | str | dict[Any, Any]:
1920
"""
2021
Resolves the ideal parameter and value amongst an optional list.
22+
Uses marshal_func if provided.
2123
"""
2224

23-
# Get the first non-empty parameter
25+
# Try to resolve using non-None value
2426
for possibility in possibilities:
2527
if possibility.value is not None:
28+
if possibility.marshal_func is not None:
29+
return {possibility.param : possibility.marshal_func(possibility.value, possibility.default)}
2630
return {possibility.param: possibility.value}
2731

28-
# Get the first non-empty default
32+
# Try to resolve using non-None default
2933
for possibility in possibilities:
3034
if possibility.default is not None:
35+
if possibility.marshal_func is not None:
36+
# When no actual value, call with None as value
37+
return {possibility.param : possibility.marshal_func(None, possibility.default)}
3138
return {possibility.param: possibility.default}
3239

33-
# If required, raise an error
40+
# If required but unresolved, raise an error
3441
if is_required:
3542
possibilities_keys = " or ".join(
3643
[possibility.param for possibility in possibilities]
3744
)
3845
raise ValueError(f"one of ${possibilities_keys} must be present")
3946

40-
# Else, return an empty dict
47+
# Else, return empty dict
4148
return {}

0 commit comments

Comments
 (0)