Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Detect type mismatch between pattern-matched variable and cases #16128

Closed
smheidrich opened this issue Sep 16, 2023 · 2 comments
Labels

Comments

@smheidrich
Copy link

Feature

It would be great if Mypy could detect and report as errors case patterns that are not possible given the type of the variable being matched on.

Pitch

Consider e.g.:

class A:
  ...

class B:
  ...

a: A = A()

match a:
  case B():
    ...

We know with certainty that variable a is of type A, so having a case to check whether it's an instance of B (which is not a subtype of A) makes no sense and indicates a type error. Yet the latest Mypy version (1.5.1) doesn't report it as one. In my opinion, it would be better if it did (and that would have been my expectation before I tested it), given that all necessary type information is explicit & static and doesn't even have to be inferred.

Objections I could think of

One could object that this isn't that different from a feature request asking that similarly "impossible" isinstance checks be treated as errors, but I would say they are different in that match/case is part of the syntax, while isinstance is "just a function" and giving its arguments special treatment (= extra type checking that takes into account its semantics) would seem odd.

Related issues

@ikonst
Copy link
Contributor

ikonst commented Sep 16, 2023

We have a check for unreachable code which also covers impossible isinstance checks. The thing is, unless A is @final, you can have C(A, B) such that

a: A = C()

@smheidrich
Copy link
Author

Damn, I hadn't thought of that, sorry :-/ Closing this then, thanks for the quick response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants