Skip to content

Commit

Permalink
support resolve generic types that doesn't specify any type arguments.
Browse files Browse the repository at this point in the history
  • Loading branch information
nrbnlulu committed Dec 24, 2024
1 parent 979b77f commit da270e7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
9 changes: 6 additions & 3 deletions aioinject/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,12 @@ async def resolve(
for base in orig_bases:
if is_generic_alias(base):
args = base.__args__
params = base.__origin__.__parameters__
for param, arg in zip(params, args, strict=False):
args_map[param.__name__] = arg
if params := getattr(base.__origin__, "__parameters__", None):
for param, arg in zip(params, args, strict=False):
args_map[param.__name__] = arg
if not args_map:
# type may be generic though user didn't provide any type parameters
type_is_generic = False


for dependency in provider.resolve_dependencies(
Expand Down
18 changes: 18 additions & 0 deletions tests/features/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,21 @@ def __init__(self, service: TwoGeneric[T, str]) -> None:
assert isinstance(instance.service.b, WithGenericDependency)
assert instance.service.a.dependency == MEANING_OF_LIFE_INT
assert instance.service.b.dependency == MEANING_OF_LIFE_STR



async def test_can_resolve_generic_class_without_parameters() -> None:
class GenericClass(Generic[T]):
def __init__(self, a: int) -> None:
self.a = a

def so_generic(self) -> T: # pragma: no cover
raise NotImplementedError

container = Container()
container.register(Scoped(GenericClass), Object(MEANING_OF_LIFE_INT))

async with container.context() as ctx:
instance = await ctx.resolve(GenericClass)
assert isinstance(instance, GenericClass)
assert instance.a == MEANING_OF_LIFE_INT

0 comments on commit da270e7

Please sign in to comment.