ThirVondukr / aioinject

Async-first python dependency injection library
https://thirvondukr.github.io/aioinject/
MIT License
30 stars 2 forks source link

Typing of context manager #10

Closed trollfot closed 7 months ago

trollfot commented 7 months ago

Currently, to allow a proper discovery of the type, the provider uses the direct annotation. In case of Context Managers, this is a bit hairy, as they should be collections.abc.Iterator or collections.abc.Generator. Should we try to make this work ?

trollfot commented 7 months ago

hm... I feel silly, since this seems to be tested and implemented. Yet, in my code, it does not work.

trollfot commented 7 months ago

I confirm that the "type_" returned is not correct :

collections.abc.Iterator[sqlmodel.orm.session.Session]

It seems that my function :

    @contextmanager
    def sqlsession(self) -> Iterator[Session]:
        with Session(self.engine) as session:
            try:
                yield session
            except Exception:
                # maybe log.
                raise
            else:
                session.commit()

does not qualify as inspect.isgeneratorfunction

trollfot commented 7 months ago

Ok, it seems I found the problem. I was using the decorator "@beartype" on the class, that also wraps every method. When checking for the wrapped function, the code only unwraps one level.

trollfot commented 7 months ago

I don't know if that's a common usecase, that we could be providing factories decorated multiple times. The function _guess_return_type could be using inspect.unwrap to recover the canonical function, instead of

        maybe_wrapped = getattr(  # @functools.wraps
            factory,
            "__wrapped__",
            factory,
        )
ThirVondukr commented 7 months ago

I'll take a look

trollfot commented 7 months ago

Let me know if I can provide some assistance or if I need to write a test to demonstrate the usecase !

ThirVondukr commented 7 months ago

If you don't mind installing from git again:

git+https://github.com/ThirVondukr/aioinject.git@b446776ad9d74ab5fb9c3af6170e8c5b7a24a734

I just tested it on a function with multiple decorators, if everything is ok I could make a release

trollfot commented 7 months ago

tested and working !