python-injector / injector

Python dependency injection framework, inspired by Guice
BSD 3-Clause "New" or "Revised" License
1.29k stars 81 forks source link

Mypy error when getting abstract classes #143

Open davidparsson opened 4 years ago

davidparsson commented 4 years ago

Using Injector to bind a concrete class to an abstract interface, and then getting an instance of that interface causes a mypy error:

class MyABC(ABC): pass
class MyClass(MyABC): pass

injector = Injector()
injector.binder.bind(MyABC, to=MyClass)  # error: Only concrete class can be given where "Type[MyABC]" is expected
injector.get(MyABC)  # error: Only concrete class can be given where "Type[MyABC]" is expected

I hope that this can be resolved by fixing type hints (although it's certainly possible to configure Injector so that the type hints will be incorrect).

jstasiak commented 4 years ago

This is unfortunate. I think this is MyPy/typing territory though as I don't believe we have any other tools to express this right now. See https://github.com/python/mypy/issues/4717 for a discussion on this.

davidparsson commented 4 years ago

Got it! Let's hope for an upstream resolution.

Thanks for a timely response, as always! 🏅

davidparsson commented 4 years ago

Newer Injector versions with more type hints causes the bind() call to fail with the same error, so I've updated the example to reflect this.

davidparsson commented 1 year ago

As of v0.991, mypy has a dedicated error code for this. With type-abstract this error can at least suppressed. A maintainer indicated that this might be as good at it gets.

See the release notes for more information.