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

fix Support nested generics #20 #21

Merged
merged 20 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
73 changes: 68 additions & 5 deletions aioinject/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@

import contextvars
import inspect
import types
import typing as t
from collections.abc import Callable, Coroutine, Iterable, Mapping, Sequence
from contextvars import ContextVar
from types import TracebackType
from types import GenericAlias, TracebackType
from typing import (
TYPE_CHECKING,
Any,
Generic,
TypeGuard,
TypeVar,
overload,
)
Expand Down Expand Up @@ -69,8 +72,27 @@ def register(self, provider: Provider[Any]) -> None:
self._providers[provider.type_] = provider


def is_generic_alias(type_: Any) -> TypeGuard[GenericAlias]:
# we currently don't support tuple, list, dict, set, type
return isinstance(
type_,
types.GenericAlias | t._GenericAlias, # type: ignore[attr-defined] # noqa: SLF001
) and t.get_origin(type_) not in (tuple, list, dict, set, type)


def get_orig_bases(type_: type) -> tuple[type, ...] | None:
return getattr(type_, "__orig_bases__", None)


def get_typevars(type_: Any) -> list[t.TypeVar] | None:
if is_generic_alias(type_):
args = t.get_args(type_)
return [arg for arg in args if isinstance(arg, t.TypeVar)]
return None


class InjectionContext(_BaseInjectionContext[ContextExtension]):
async def resolve(
async def resolve( # noqa: C901
self,
type_: type[_T],
) -> _T:
Expand All @@ -80,12 +102,53 @@ async def resolve(
return cached

dependencies = {}
args_map: dict[str, Any] = {}
type_is_generic = False
if is_generic_alias(type_):
type_is_generic = True
args = type_.__args__
params: dict[str, Any] = {
param.__name__: param
for param in type_.__origin__.__parameters__ # type: ignore[attr-defined]
}
args_map = dict(zip(params.keys(), args, strict=False))
elif orig_bases := get_orig_bases(type_):
type_is_generic = True
# find the generic parent
for base in orig_bases:
if is_generic_alias(base):
args = base.__args__
if params := {
param.__name__: param
for param in getattr(
base.__origin__, "__parameters__", ()
)
}:
args_map.update(
dict(zip(params, args, strict=False)),
)
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(
self._container.type_context,
):
dependencies[dependency.name] = await self.resolve(
type_=dependency.type_,
)
dep_type = dependency.type_
if type_is_generic and (dep_args := get_typevars(dep_type)):
# This is a generic type, we need to resolve the type arguments
# and pass them to the provider.
resolved_args = [args_map[arg.__name__] for arg in dep_args]
origin = t.get_origin(dep_type)
assert origin is not None # noqa: S101
resolved_type = dep_type.__getitem__(*resolved_args) # type: ignore[index]
dependencies[dependency.name] = await self.resolve(
type_=resolved_type,
)
else:
dependencies[dependency.name] = await self.resolve(
type_=dep_type,
)

if provider.lifetime is DependencyLifetime.singleton:
async with store.lock(provider) as should_provide:
Expand Down
125 changes: 125 additions & 0 deletions tests/features/test_generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,128 @@ async def test_resolve_generics(
async with container.context() as ctx:
instance = await ctx.resolve(type_)
assert isinstance(instance, instanceof)


class NestedGenericService(Generic[T]):
def __init__(self, service: T) -> None:
self.service = service


MEANING_OF_LIFE_INT = 42
MEANING_OF_LIFE_STR = "42"


class Something:
def __init__(self) -> None:
self.a = MEANING_OF_LIFE_INT


async def test_nested_generics() -> None:
container = Container()
container.register(
Scoped(NestedGenericService[WithGenericDependency[Something]]),
Scoped(WithGenericDependency[Something]),
Scoped(Something),
Object(MEANING_OF_LIFE_INT),
Object("42"),
)

async with container.context() as ctx:
instance = await ctx.resolve(
NestedGenericService[WithGenericDependency[Something]]
)
assert isinstance(instance, NestedGenericService)
assert isinstance(instance.service, WithGenericDependency)
assert isinstance(instance.service.dependency, Something)
assert instance.service.dependency.a == MEANING_OF_LIFE_INT


class TestNestedUnresolvedGeneric(Generic[T]):
def __init__(self, service: WithGenericDependency[T]) -> None:
self.service = service


async def test_nested_unresolved_generic() -> None:
container = Container()
container.register(
Scoped(TestNestedUnresolvedGeneric[int]),
Scoped(WithGenericDependency[int]),
Object(42),
Object("42"),
)

async with container.context() as ctx:
instance = await ctx.resolve(TestNestedUnresolvedGeneric[int])
assert isinstance(instance, TestNestedUnresolvedGeneric)
assert isinstance(instance.service, WithGenericDependency)
assert instance.service.dependency == MEANING_OF_LIFE_INT


async def test_nested_unresolved_concrete_generic() -> None:
class GenericImpl(TestNestedUnresolvedGeneric[str]):
pass

container = Container()
container.register(
Scoped(GenericImpl),
Scoped(WithGenericDependency[str]),
Object(42),
Object("42"),
)

async with container.context() as ctx:
instance = await ctx.resolve(GenericImpl)
assert isinstance(instance, GenericImpl)
assert isinstance(instance.service, WithGenericDependency)
assert instance.service.dependency == "42"


async def test_partially_resolved_generic() -> None:
K = TypeVar("K")

class TwoGeneric(Generic[T, K]):
def __init__(
self, a: WithGenericDependency[T], b: WithGenericDependency[K]
) -> None:
self.a = a
self.b = b

class UsesTwoGeneric(Generic[T]):
def __init__(self, service: TwoGeneric[T, str]) -> None:
self.service = service

container = Container()
container.register(
Scoped(UsesTwoGeneric[int]),
Scoped(TwoGeneric[int, str]),
Scoped(WithGenericDependency[int]),
Scoped(WithGenericDependency[str]),
Object(MEANING_OF_LIFE_INT),
Object("42"),
)

async with container.context() as ctx:
instance = await ctx.resolve(UsesTwoGeneric[int])
assert isinstance(instance, UsesTwoGeneric)
assert isinstance(instance.service, TwoGeneric)
assert isinstance(instance.service.a, WithGenericDependency)
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:
Copy link
Contributor Author

@nrbnlulu nrbnlulu Dec 29, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need to find the usecase where I needed this.

Copy link
Contributor

@fadedDexofan fadedDexofan Jan 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nrbnlulu TypeVar with default in new Python versions or all impls (after #22) for generic interface

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
Loading