Skip to content

Commit

Permalink
fix: unravel Optional to inner generic arg from instance (#2172)
Browse files Browse the repository at this point in the history
* fix: unravel Optional to inner generic arg from instance

* test: remove dependency on Incremental in common

* refactor: use extract_inner_type

* refactor: remove redundant conditional
  • Loading branch information
otosky authored Dec 28, 2024
1 parent 5afa6ce commit 2f20cc4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
3 changes: 1 addition & 2 deletions dlt/common/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,8 +438,7 @@ def get_generic_type_argument_from_instance(
"""
orig_param_type = Any
if cls_ := getattr(instance, "__orig_class__", None):
# instance of generic class
pass
cls_ = extract_inner_type(cls_)
elif bases_ := get_original_bases(instance.__class__):
# instance of class deriving from generic
cls_ = bases_[0]
Expand Down
23 changes: 23 additions & 0 deletions tests/common/test_typing.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from types import SimpleNamespace

import pytest
from dataclasses import dataclass
from typing import (
Any,
Callable,
ClassVar,
Final,
Generic,
List,
Literal,
Mapping,
Expand Down Expand Up @@ -44,6 +47,7 @@
is_annotated,
is_callable_type,
add_value_to_literal,
get_generic_type_argument_from_instance,
)


Expand Down Expand Up @@ -310,3 +314,22 @@ 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:
T = TypeVar("T")

class Foo(Generic[T]):
pass

# generic contains hint
instance = SimpleNamespace(__orig_class__=Foo[str])
assert get_generic_type_argument_from_instance(instance) is str
instance = SimpleNamespace(__orig_class__=Optional[Foo[str]])
assert get_generic_type_argument_from_instance(instance) is str

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

0 comments on commit 2f20cc4

Please sign in to comment.