-
-
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
Allow narrowing enum values using == #11521
Conversation
Resolves python#10915, resolves python#9786 See the discussion in python#10915. I'm sympathetic to the difference between identity and equality here being surprising and that mypy doesn't usually make concessions to mutability when type checking. The old test cases are pretty explicit about their intentions and are worth reading. Curious to see what people (and mypy-primer) have to say about this.
Diff from mypy_primer, showing the effect of this PR on open source code: porcupine (https://github.com/Akuli/porcupine.git)
+ porcupine/pluginloader.py:350: error: Statement is unreachable [unreachable]
|
My gut feeling is that |
IIRC, treating == and is differently was intended to be a workaround for tests that mutate state and repeatedly do something like That latter assert would end up narrowing away In retrospect, I'm wondering if a better solution might have been to instead overhaul our heuristics for when narrowing happens in general. At the moment, I think in practice the only time you'd want to narrow literals is in if/else statements, so sticking to just narrowing there might be good enough. Or maybe alternatively, allow literal-type narrowing to sometimes change the type instead of narrowing it? Higher-level, the problem is that unconditional narrowing combined with mutable state is fundamentally unsound: you can run into the exact same problem even with Unfortunately, this "always narrow" heuristic doesn't work as well for literal types, which is why I ended up adding a bunch of misc ad-hoc heuristics such as "narrow enums only when using 'is'" to try and patch things up. In any case, I do agree the heuristics I ended up picking out are unintuitive and probably ought to be changed. But IMO we should probably design and implement better heuristics first before landing this PR to avoid causing too large of a drop in type-checking coverage for users. |
This keeps coming up in issues, so I'm going to merge this. The status quo is unintuitive and users can still narrow to the bottom type using |
Resolves #10915, resolves #9786
See the discussion in #10915. I'm sympathetic to the difference between
identity and equality here being surprising and that mypy doesn't
usually make concessions to mutability when type checking.
The old test cases are pretty explicit about their intentions and are
worth reading. Curious to see what people (and mypy-primer) have to say
about this.