python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Add support for typing.Annotated

Open maintain0404 opened this issue 2 years ago • 7 comments

Resolve #693.

This PR supports using typing.Annotated instead of parameter defaults when defining markers.

maintain0404 avatar Jul 09 '23 09:07 maintain0404

This addition is really nice! I hope it will be merged

TimNekk avatar Dec 06 '23 21:12 TimNekk

@TimNekk Agreed! Have been watching this PR for a while now 🍿

mquinnfd avatar Dec 08 '23 11:12 mquinnfd

This would be really nice to have, perhaps it would make a bigger chance of getting merged in this fork: https://github.com/anton-petrov/python-dependency-injector ?

4c0n avatar Mar 01 '24 10:03 4c0n

@4c0n If this commit is used, rather than the copied code, you're welcome.

maintain0404 avatar Mar 07 '24 03:03 maintain0404

@maintain0404 sorry for submitting a review by mistake. I was just checking the changes.

I hope your PR get merged soon! However I noticed that your implementation don't support injections into modules and class attributes.

The following code should add support for that:

def _get_members_and_annotated(obj: Any) -> list[tuple[str, Any]]:
    members = inspect.getmembers(obj)
    for ann_name, annotation in inspect.get_annotations(obj).items():
        if get_origin(annotation) is Annotated:
            member = get_args(annotation)[1]
            members.append((ann_name, member))
    return members

And then in wire you use that function instead of inspect.getmembers:

def wire(  # noqa: C901
    container: Container,
    *,
    modules: Optional[Iterable[ModuleType]] = None,
    packages: Optional[Iterable[ModuleType]] = None,
) -> None:
    ....
    for module in modules:
        for member_name, member in _get_members_and_annotated(module):
             ...
             elif inspect.isclass(member):
                cls = member
                try:
                    cls_members = _get_members_and_annotated(cls)
                except Exception:  # noqa
                    # Hotfix, see: https://github.com/ets-labs/python-dependency-injector/issues/441
                    continue

abdok96 avatar Mar 28 '24 14:03 abdok96

Hey, is this dead? Why didn't this get merged?

JobaDiniz avatar Jul 30 '24 00:07 JobaDiniz