python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.22k stars 2.78k forks source link

mypy doesnt use unitest.TestCase.assertIsInstance checks for type narrowing #13038

Open rahulporuri opened 2 years ago

rahulporuri commented 2 years ago

Apologies if i'm using the wrong words to describe what i'm trying to recommend/request.

Feature

At the moment, mypy recommends type narrowing using asserts. For example, if something is Optional[None], add assert something is not None to help mypy type check the statements that follow the assert.

In tests, instead of adding an additional assert, can mypy use a unittest.TestCase.assertIsInstance check?

Pitch

Most unittest-based tests already make use of the assertIsInstance check so we can prevent the need to add an additional assert or the need to convert the assertIsInstance into a assert isinstance(something) is sometype.

rahulporuri commented 2 years ago

Hey @AlexWaygood, i'm not sure how to fix this but with some handholding, I might be able to open a PR. I'm not even sure what direction to look in at the moment.

erictraut commented 2 years ago

This would require special-casing this particular method in the type checker. There is precedent for doing this for certain important built-in methods, but it's generally fragile because it overrides the type information provided in the typeshed stub, and if the stub changes, the override logic can break. The maintainers of mypy would need to decide whether it's worth doing so in this case.

If it is decided that this isn't desirable in the mypy code base, you could choose to write a mypy extension for your own use that adds this functionality.

The more general way to fix this is to introduce a new feature to the type system. I've proposed an extension to PEP 647 called TypeAssert that would allow for the proper annotation of this method in the type stub, but the proposal hasn't yet made it to the PEP phase.

rahulporuri commented 2 years ago

thanks for the clarification @erictraut . I'll leave it to you to decide if this issue should be closed as a wont-close.

eltoder commented 1 year ago

@erictraut Was there any progress on your proposed extension? If not, do you think it's possible to separate TypeAssert into a separate proposal? Hopefully it is not controversial and there is a clear example in the standard library where it is needed.

erictraut commented 1 year ago

There hasn't been any progress on the TypeAssert extension. You're welcome to champion it and create a new PEP if you see fit.