injector icon indicating copy to clipboard operation
injector copied to clipboard

Mypy error when getting abstract classes

Open davidparsson opened this issue 5 years ago • 4 comments

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).

davidparsson avatar Apr 22 '20 08:04 davidparsson

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.

jstasiak avatar Apr 22 '20 09:04 jstasiak

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

Thanks for a timely response, as always! 🏅

davidparsson avatar Apr 22 '20 11:04 davidparsson

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 avatar Jun 22 '20 12:06 davidparsson

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.

davidparsson avatar Jan 19 '23 09:01 davidparsson