Skip to content

Commit

Permalink
Merge pull request #61 from altescy/support-generic-classes
Browse files Browse the repository at this point in the history
Support generic registrable
  • Loading branch information
altescy authored Apr 9, 2024
2 parents 26bbe82 + 71c6987 commit be6efe6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
15 changes: 10 additions & 5 deletions colt/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,17 @@ def _get_constructor_by_name(
annotation: Optional[Type[T]] = None,
allow_to_import: bool = True,
) -> Union[Type[T], Callable[..., T]]:
origin: Any
if isinstance(annotation, type):
origin = annotation
else:
origin = typing.get_origin(annotation) if annotation else None
if (
annotation
and isinstance(annotation, type)
and issubclass(annotation, Registrable)
origin is not None
and isinstance(origin, type)
and issubclass(origin, Registrable)
):
constructor = cast(Type[T], annotation.by_name(name, allow_to_import))
constructor = cast(Type[T], origin.by_name(name, allow_to_import))
else:
constructor = cast(Type[T], DefaultRegistry.by_name(name, allow_to_import))

Expand All @@ -107,7 +112,7 @@ def _is_namedtuple(cls: Type[T]) -> bool:
fields = getattr(cls, "_fields", None)
if not isinstance(fields, tuple):
return False
return all(type(name) == str for name in fields)
return all(type(name) is str for name in fields)

@staticmethod
def _catname(parent: str, *keys: Union[int, str]) -> str:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_generics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import Generic, TypeVar

import colt

T = TypeVar("T")


def test_generic_registrable_can_be_built() -> None:
class Foo(colt.Registrable, Generic[T]):
...

@Foo.register("bar")
class Bar(Foo[int]):
...

class Container:
def __init__(self, foo: Foo[T]) -> None:
self.foo = foo

container = colt.build({"foo": {"@type": "bar"}}, Container)
assert isinstance(container, Container)
assert isinstance(container.foo, Bar)

0 comments on commit be6efe6

Please sign in to comment.