adriangb / di

Pythonic dependency injection
https://www.adriangb.com/di/
MIT License
301 stars 13 forks source link

enhancement: dependent call should handle class __call__ when it is generator #106

Closed maxzhenzhera closed 1 year ago

maxzhenzhera commented 1 year ago

Example

Here I use factory (dependent call) as a configurable class with __call__: https://github.com/maxzhenzhera/di/blob/5302c792bad2f3ee0dc8fae6116756e088b95f87/docs_src/bug_callalbe_class_instance_not_handled_as_factory.py

    with container.enter_scope("request") as state:
        db = solved.execute_sync(executor=SyncExecutor(), state=state)
        print(db)  # <generator object PostgresFactory.__call__ at 0x7f52f19657e0>

But __call__ is not handled and I got just a raw generator.

Workaround

It works if I simply put __call__ as dependent call:

    container.bind(
        bind_by_type(
            Dependent(
                PostgresFactory(db_config).__call__,
                scope="request",
            ),
            DBProtocol,
        ),
    )

Result:

    with container.enter_scope("request") as state:
        db = solved.execute_sync(executor=SyncExecutor(), state=state)
        print(db)
        # Postgres init-ed
        # <__main__.Postgres object at 0x7f1d09713400>
        # Postgres closed

Handling of this case fixed in one Fastapi`s PR: https://github.com/tiangolo/fastapi/pull/1365