Skip to content
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

instancify_args: support Optional dataclasses #139

Merged
merged 1 commit into from
Feb 18, 2022
Merged
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
18 changes: 16 additions & 2 deletions src/saturn_engine/core/pipeline.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import typing
from typing import Any
from typing import Callable
from typing import cast
Expand Down Expand Up @@ -48,8 +49,21 @@ def instancify_args(args: dict[str, object], pipeline: Callable) -> None:
if not isinstance(data, dict):
continue

if dataclasses.is_dataclass(parameter.annotation):
schema = schema_for(parameter.annotation)
target_type = parameter.annotation

# Support Optional[dataclass], which is very common.
# This does not support Union of two dataclasses yet.
if typing.get_origin(target_type) is typing.Union:
target_args = [
arg
for arg in typing.get_args(target_type)
if not isinstance(None, arg)
]
if len(target_args) == 1:
target_type = target_args[0]

if dataclasses.is_dataclass(target_type):
schema = schema_for(target_type)
args[parameter.name] = schema.load(data)


Expand Down
23 changes: 23 additions & 0 deletions tests/core/test_pipeline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import Optional

import dataclasses

from saturn_engine.core.pipeline import PipelineInfo


def test_instancify_args_optional() -> None:
@dataclasses.dataclass
class A:
field: str

def pipeline(a: Optional[A]) -> None:
pass

args: dict[str, object] = {"a": {"field": "value"}}

PipelineInfo.instancify_args(
args=args,
pipeline=pipeline,
)

assert args == {"a": A(field="value")}