From 1a29a294d376c8213fc9c54f2ee74beffccc969a Mon Sep 17 00:00:00 2001 From: Rodrigo Martins Higuti de Oliveira Date: Fri, 12 Jul 2024 13:57:18 -0300 Subject: [PATCH] WIP return Annotated on Autowired new cls call --- injectable/autowiring/autowired_decorator.py | 12 ++++++++++-- injectable/autowiring/autowired_type.py | 7 +++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/injectable/autowiring/autowired_decorator.py b/injectable/autowiring/autowired_decorator.py index c3c1783..19f8687 100644 --- a/injectable/autowiring/autowired_decorator.py +++ b/injectable/autowiring/autowired_decorator.py @@ -85,7 +85,7 @@ def wrapper(*args, **kwargs): def _get_parameter_annotation(parameter) -> Union[type, _Autowired]: if isinstance(parameter.annotation, _AnnotatedAlias): autowired_annotations = list( - filter(lambda t: _is_autowired(t), get_args(parameter.annotation)) + filter(lambda t: _is_autowired(t), _get_args_flattened(parameter.annotation)) ) if len(autowired_annotations) == 0: return parameter.annotation @@ -93,7 +93,7 @@ def _get_parameter_annotation(parameter) -> Union[type, _Autowired]: raise AutowiringError("Multiple Autowired annotations found") autowired_annotation = autowired_annotations[0] if not isinstance(autowired_annotation, _Autowired): - return autowired_annotation(dependency=get_args(parameter.annotation)[0]) + return get_args(autowired_annotation(dependency=get_args(parameter.annotation)[0]))[1] if autowired_annotation.dependency is None: return type(autowired_annotation)( dependency=get_args(parameter.annotation)[0], @@ -111,3 +111,11 @@ def _is_autowired(annotation) -> bool: return isinstance(annotation, _Autowired) or ( inspect.isclass(annotation) and issubclass(annotation, Autowired) ) + + +def _get_args_flattened(annotation) -> list: + return [ + arg + for e in get_args(annotation) + for arg in (_get_args_flattened(e) if isinstance(e, _AnnotatedAlias) else [e]) + ] diff --git a/injectable/autowiring/autowired_type.py b/injectable/autowiring/autowired_type.py index f950714..e898d25 100644 --- a/injectable/autowiring/autowired_type.py +++ b/injectable/autowiring/autowired_type.py @@ -1,4 +1,4 @@ -from typing import Union, TypeVar, Sequence +from typing import Union, TypeVar, Sequence, Annotated import typing_inspect @@ -144,10 +144,13 @@ def __new__( exclude_groups: Sequence[str] = None, lazy: bool = False, ) -> T: - return _Autowired( + instance = _Autowired( dependency, namespace=namespace, group=group, exclude_groups=exclude_groups, lazy=lazy, ) + if dependency is None: + return instance + return Annotated[dependency, instance]