Skip to content

Commit

Permalink
fix: unravel Optional to inner generic arg from instance
Browse files Browse the repository at this point in the history
  • Loading branch information
otosky committed Dec 22, 2024
1 parent 5a1cb69 commit 1877b2d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions dlt/common/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,10 @@ def get_generic_type_argument_from_instance(
"""
orig_param_type = Any
if cls_ := getattr(instance, "__orig_class__", None):
# unfurl Optional[Incremental[...]] to Incremental[...]
if is_optional_type(cls_):
cls_ = get_args(cls_)[0]

# instance of generic class
pass
elif bases_ := get_original_bases(instance.__class__):
Expand Down
18 changes: 18 additions & 0 deletions tests/common/test_typing.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from types import SimpleNamespace

import pytest
from dataclasses import dataclass
from typing import (
Expand Down Expand Up @@ -44,7 +46,9 @@
is_annotated,
is_callable_type,
add_value_to_literal,
get_generic_type_argument_from_instance,
)
from dlt.extract import Incremental


class TTestTyDi(TypedDict):
Expand Down Expand Up @@ -310,3 +314,17 @@ def test_add_value_to_literal() -> None:
add_value_to_literal(TestSingleLiteral, "green")
add_value_to_literal(TestSingleLiteral, "blue")
assert get_args(TestSingleLiteral) == ("red", "green", "blue")


def test_get_generic_type_argument_from_instance() -> None:
# generic contains hint
instance = SimpleNamespace(__orig_class__=Incremental[str])
assert get_generic_type_argument_from_instance(instance) is str
instance = SimpleNamespace(__orig_class__=Optional[Incremental[str]])
assert get_generic_type_argument_from_instance(instance) is str

# with sample values
instance = SimpleNamespace(__orig_class__=Incremental[Any])
assert get_generic_type_argument_from_instance(instance, 1) is int
instance = SimpleNamespace(__orig_class__=Optional[Incremental[Any]])
assert get_generic_type_argument_from_instance(instance, 1) is int

0 comments on commit 1877b2d

Please sign in to comment.