ets-labs / python-dependency-injector

Dependency injection framework for Python
https://python-dependency-injector.ets-labs.org/
BSD 3-Clause "New" or "Revised" License
3.9k stars 304 forks source link

mypy error: "FastAPI" has no attribute "container" #626

Open SpyrosRoum opened 2 years ago

SpyrosRoum commented 2 years ago

dependecy-injector version: "^4.40.0" FastAPI version: "^0.79.1"

Hello, following the example for FastAPI, mypy complains with the error on the title when I do app.container = container.

The only way I found to work around it (other than type: ignore) was to create a custom class that inherits from FastAPI:

class MyFastAPI(FastAPI):
    container: Container

def create_app() -> MyFastAPI:
    app = MyFastAPI()

    container = Container()
    app.container = container

    @app.on_event('startup')
    async def startup_event() -> None:
        app.container.wire(modules=[__name__])
        await initialize(app.container)

    return app

Is there any other way to do this? I'm a little surprised that I couldn't find any other issue about this so I'm wondering if I missed something.

ffss92 commented 1 year ago

I mean, is that really a work around? You needed to add a new property to the FastAPI class so you extended it. Seems like a normal solution.

SpyrosRoum commented 1 year ago

You are right that this is a fairly good solution, I'm just mostly surprised that this was not mentioned anywhere and I wasn't able to find any issues or anything else about it.

For a lib that claims to be mypy friendly I'd expect it to mention something instead of just giving an example that doesn't actually work with mypy

ffss92 commented 1 year ago

FastAPI is a third party package though, I think 'mypy fiendly' means that the lib provides it's own types.

sh-at-cs commented 1 month ago

I'm curious how/why setting app.container actually makes things work - is this an internal (hence untyped) attribute of FastAPI that we are setting to make FastAPI use our own dependency container somehow, or does python-dependency-injector have special logic for injecting itself into FastAPI that looks for this attribute on the FastAPI app? Is this documented anywhere?

ZipFile commented 1 month ago

It doesn't, mypy is right here. There is no special attribute-checking logic in python-dependency-injector neither FastAPI has container attribute. More idiomatic way would be something like #683.