-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
Exhaustiveness checks (assert_never) don't work with 2-tuple of enums #16722
Comments
Insted of using asser_never function you can directly raise an AssertionError exception like mentioned in the below code ` class A(Enum): class B(Enum): def test(a: A, b: B) -> bool: |
@sidddhesh100 I just did an |
Exhaustiveness checks are based on type narrowing. The original type of the subject expression ( Narrowing this type based on the specified patterns requires "tuple expansion", which is not something mypy currently does, at least to my knowledge. The tuple expansion of the above type is As you can see, this technique can lead to a union with a very large number of subtypes. Type checkers generally try to avoid such combinatoric explosions, so even if mypy were to add support for this technique, it would likely need to place limits on the expansion. FWIW, pyright does tuple expansion but only for one dimension of a tuple at a time. That means pyright also doesn't detect exhaustiveness in the code sample above, since it requires expansion of two tuple dimensions. If you restructure your code to avoid the need for tuple expansion, mypy will then be able to perform exhaustiveness checks. |
Other langs with pattern matching (Rust, Haskell etc) don't seem to have an issue with this, but I've never tried for anything bigger than ~4-tuples with 2-3 variants. I don't know how other langs avoid the explosion or if they just tolerate it, but this is a totally standard use of tuples and pattern matching and I think anybody coming from those langs (which AFAICT inspired the feature in Python) would expect it to work. |
two cases with different, but wrong results (mypy 1.111):
|
Any updates on this? It would be a nice to have. Not sure if the type explosion is really a problem. For most of the cases, we do not use type matching so big that this becomes a problem (I think, I have not got any data to back that statement). |
Bug Report
The code below fails to type check, but should succeed because it's exhaustive.
There are some possibly related issues, but I don't know if they are all the same bug, the other tickets tend to depend on
Union
which this does not: #16650 #15426 #12364To Reproduce
Playground link: https://mypy-play.net/?mypy=latest&python=3.12&gist=0d21d288fce8aa13d3cc60f4e418960a
Actual Behavior
Your Environment
mypy.ini
(and other config files): n/aThe text was updated successfully, but these errors were encountered: