Plugin interface for type narrowing on `==` comparisons
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Feature
I'm proposing a new plugin interface for type narrowing on == comparisons.
Pitch
Take the following code:
from enum import IntEnum
class MyIntEnum(IntEnum):
A = 1
B = 2
m: MyIntEnum
if m == 1:
pass
else:
reveal_type(m)
This should reveal MyIntEnum.B, but mypy can't know that because it has no idea about how the __eq__ method on MyIntEnum works.
A plugin interface together with a builtin plugin could fix that.
mypy would walk through the MyIntEnum MRO until it encounters a class that defines __eq__ and then look for a plugin able to handle this class.
The plugin matching the class will be called and can return two types. One narrowing for if the condition matches and one for if it doesn't.
This would also be useful for checking match statements (#10191). Currently I have to special case enums there, as match always compares emums with ==, while mypy only narrows types if enums are compared with is.
It would probably also make it possible to get rid of the special casing of a == type(A) and replace it with a plugin.
I would like to first hear some opinions about this before I start implementing it.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing mypy's existing plugin interfaces and the current enum narrowing behavior for == versus is. Then examine the match-statement case referenced in #10191 and define how a plugin would return narrowing types for matching and non-matching comparisons.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 20/100