Skip to content

fix(core): support marshal func in one of #1073

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added docs/module.rst
Empty file.
31 changes: 23 additions & 8 deletions scaleway-core/scaleway_core/utils/resolve_one_of.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,56 @@
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, Dict, Generic, List, Optional, TypeVar

from scaleway_core.profile import ProfileDefaults

T = TypeVar("T")


@dataclass
class OneOfPossibility(Generic[T]):
param: str

value: Optional[T]

default: Optional[T] = None
default: Optional[T | ProfileDefaults] = None
marshal_func: Optional[Callable[[T, T | None], Dict[str, Any]]] = None


def resolve_one_of(
possibilities: List[OneOfPossibility[Any]], is_required: bool = False
) -> Dict[str, Any]:
) -> dict[Any | Any, None] | str | dict[Any, Any]:
"""
Resolves the ideal parameter and value amongst an optional list.
Uses marshal_func if provided.
"""

# Get the first non-empty parameter
# Try to resolve using non-None value
for possibility in possibilities:
if possibility.value is not None:
if possibility.marshal_func is not None:
return {
possibility.param: possibility.marshal_func(
possibility.value, possibility.default
)
}
return {possibility.param: possibility.value}

# Get the first non-empty default
# Try to resolve using non-None default
for possibility in possibilities:
if possibility.default is not None:
if possibility.marshal_func is not None:
return {
possibility.param: possibility.marshal_func(
None, possibility.default
)
}
return {possibility.param: possibility.default}

# If required, raise an error
# If required but unresolved, raise an error
if is_required:
possibilities_keys = " or ".join(
[possibility.param for possibility in possibilities]
)
raise ValueError(f"one of ${possibilities_keys} must be present")

# Else, return an empty dict
# Else, return empty dict
return {}
Loading