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

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

Open SpyrosRoum opened this issue 3 years ago • 5 comments

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.

SpyrosRoum avatar Sep 30 '22 15:09 SpyrosRoum

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.

ffss92 avatar Nov 21 '22 02:11 ffss92

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

SpyrosRoum avatar Nov 21 '22 09:11 SpyrosRoum

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

ffss92 avatar Nov 21 '22 12:11 ffss92

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?

sh-at-cs avatar Aug 27 '24 12:08 sh-at-cs

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.

ZipFile avatar Aug 29 '24 08:08 ZipFile