1
+ from collections .abc import Callable
1
2
from dataclasses import dataclass
2
3
from typing import Any , Dict , Generic , List , Optional , TypeVar
4
+ from _typeshed import SupportsKeysAndGetItem
5
+
6
+ from scaleway_core .profile import ProfileDefaults
3
7
4
8
T = TypeVar ("T" )
5
9
6
10
7
11
@dataclass
8
12
class OneOfPossibility (Generic [T ]):
9
13
param : str
10
-
11
14
value : Optional [T ]
12
-
13
- default : Optional [T ] = None
15
+ default : Optional [ T | ProfileDefaults ] = None
16
+ marshal_func : Optional [Callable [[ T , T | None ], Dict [ str , Any ]] ] = None
14
17
15
18
16
19
def resolve_one_of (
17
20
possibilities : List [OneOfPossibility [Any ]], is_required : bool = False
18
- ) -> Dict [str , Any ]:
21
+ ) -> SupportsKeysAndGetItem [str , Any ]:
19
22
"""
20
23
Resolves the ideal parameter and value amongst an optional list.
24
+ Uses marshal_func if provided.
21
25
"""
22
26
23
- # Get the first non-empty parameter
27
+ # Try to resolve using non-None value
24
28
for possibility in possibilities :
25
29
if possibility .value is not None :
30
+ if possibility .marshal_func is not None :
31
+ return {
32
+ possibility .param : possibility .marshal_func (
33
+ possibility .value , possibility .default
34
+ )
35
+ }
26
36
return {possibility .param : possibility .value }
27
37
28
- # Get the first non-empty default
38
+ # Try to resolve using non-None default
29
39
for possibility in possibilities :
30
40
if possibility .default is not None :
31
41
if possibility .marshal_func is not None :
@@ -37,12 +47,12 @@ def resolve_one_of(
37
47
}
38
48
return {possibility .param : possibility .default }
39
49
40
- # If required, raise an error
50
+ # If required but unresolved , raise an error
41
51
if is_required :
42
52
possibilities_keys = " or " .join (
43
53
[possibility .param for possibility in possibilities ]
44
54
)
45
55
raise ValueError (f"one of ${ possibilities_keys } must be present" )
46
56
47
- # Else, return an empty dict
57
+ # Else, return empty dict
48
58
return {}
0 commit comments