Misleading warning message when using ABCMeta instead of Protocol
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
To Reproduce
I run this code, expecting it to type-check:
https://mypy-play.net/?mypy=latest&python=3.11&gist=d4c1190de2b786aea78cc801ee2e7829
Expected Behavior
I would expect an error perhaps like this:
main.py:42: error: Argument "key" to "max_if" has incompatible type "Callable[[str], Optional[int]]"; expected "Callable[[str], Optional[S]]" where S is a subclass of "Comparable" [arg-type]
Actual Behavior
main.py:42: error: Argument "key" to "max_if" has incompatible type "Callable[[str], Optional[int]]"; expected "Callable[[str], None]" [arg-type]
Found 1 error in 1 file (checked 1 source file)
Note
This was very confusing. While investigating this bug, I found out that I had to define Comparable using typing.Protocol instead of ABCMeta, and then I got the code to type-check.
I guess that since mypy tries to find S which is Comparable, so that Optional[int] would match S | None, and since it recognizes that int isn't a subclass of Comparable, it is left with the None and this is what it shows in the error message. However, this is very confusing.
Your Environment
- Mypy version used: 1.0.0
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.11
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 with the linked mypy-play reproduction and compare the diagnostics produced when Comparable uses ABCMeta versus typing.Protocol. Trace the type inference and error-reporting path for the max_if key argument. Done means the ABCMeta case produces a diagnostic that accurately explains the incompatibility rather than showing Callable[[str], None].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100