You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
main.py:42: error: Argument "key" to "max_if" has incompatible type "Callable[[str], Optional[int]]"; expected "Callable[[str], Optional[Comparable]]" [arg-type]
@tmke8 I believe that actually the function is generic in S. In my definition, Comparable means that a type is comparable to itself. The key function should return values from a specific type, which is comparable to itself. With the definition you suggested, the key function may return many different types, say int for one item and str for another.
(But even if the definition without another generic is correct, I would still want the error message to be more correct and more helpful.)
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:
Actual Behavior
Note
This was very confusing. While investigating this bug, I found out that I had to define
Comparable
usingtyping.Protocol
instead ofABCMeta
, and then I got the code to type-check.I guess that since mypy tries to find
S
which isComparable
, so thatOptional[int]
would matchS | None
, and since it recognizes thatint
isn't a subclass ofComparable
, it is left with theNone
and this is what it shows in the error message. However, this is very confusing.Your Environment
mypy.ini
(and other config files): NoneThe text was updated successfully, but these errors were encountered: