Open rahulporuri opened 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.
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.
thanks for the clarification @erictraut . I'll leave it to you to decide if this issue should be closed as a wont-close.
@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.
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.
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
isOptional[None]
, addassert something is not None
to help mypy type check the statements that follow theassert
.In tests, instead of adding an additional
assert
, can mypy use aunittest.TestCase.assertIsInstance
check?Pitch
Most unittest-based tests already make use of the
assertIsInstance
check so we can prevent the need to add an additionalassert
or the need to convert theassertIsInstance
into aassert isinstance(something) is sometype
.