Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
SpyrosRoum opened this issue Sep 30, 2022 · 5 comments
Open

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

SpyrosRoum opened this issue Sep 30, 2022 · 5 comments

Comments

@SpyrosRoum
Copy link

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
Copy link

ffss92 commented Nov 21, 2022

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
Copy link
Author

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
Copy link

ffss92 commented Nov 21, 2022

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

@sh-at-cs
Copy link

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
Copy link
Contributor

ZipFile commented Aug 29, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants