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.83k stars 304 forks source link

@injected providers are not typechecked #453

Open jack-michaud opened 3 years ago

jack-michaud commented 3 years ago

Semi-related to #452.

When using @inject, any arbitrary provider T may be provided as an argument to Provide[T] when injecting a provider without a type error.

For example, in the Flask miniapp, in examples/miniapps/flask/githubnavigator/views.py, replacing:

search_service: SearchService = Provide[Container.search_service]

with

search_service: SearchService = Provide[Container.config]

results in no issues when running mypy on this file:

$ mypy githubnavigator/views.py
Success: no issues found in 1 source file

I expected there to be a type error because Container.config is not a provider for SearchService. Is there a way to create proper typing for these providers so this error would be thrown?

rmk135 commented 3 years ago

Hi @jack-michaud , yeah, mypy does not detect this. I don’t know if there is a way to make it do that. Seems like Pyright does similar checking, but as you mentioned in #451 it causes a different problem.

rmk135 commented 3 years ago

I see you point totally reasonable but I’m not yet sure how to implement this.

EdwardBlair commented 3 years ago

https://mypy.readthedocs.io/en/stable/extending_mypy.html

Seems rather non-trivial...

Pydantic's implementation https://pydantic-docs.helpmanual.io/mypy_plugin/ https://github.com/samuelcolvin/pydantic/blob/5ccbdcb5904f35834300b01432a665c75dc02296/pydantic/mypy.py

Other examples: https://github.com/python/mypy/tree/master/mypy/plugins