Cannot create a class that supports Iterable[RichComparisonT]
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
In pandas-stubs, we'd like to be able to have a class that can be passed to the standard python sorted(), max(), min() functions, etc. But mypy doesn't seem to support this, while pyright does.
To Reproduce
from typing import TYPE_CHECKING, Iterable, Iterator, TypeVar
if TYPE_CHECKING:
from _typeshed import SupportsRichComparisonT as SRCT
else: # Use this to make the code runnable
SRCT = TypeVar("SRCT")
class MyList(Iterable[SRCT]):
def __init__(self, x: list[int]):
self._x = x
def __iter__(self) -> Iterator[int]:
for i in self._x:
yield i
foo = MyList([3, 2, 1])
print(sorted(foo))
Expected Behavior
No error reported by mypy
Actual Behavior
richcmp.py:13: error: Return type "Iterator[int]" of "__iter__" incompatible with return type "Iterator[SRCT]" in supertype "Iterable" [override]
richcmp.py:18: error: Need type annotation for "foo" [var-annotated]
Found 2 errors in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 0.991
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10
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 richcmp.py reproduction and the reported interaction between Iterable[SupportsRichComparisonT] and iter. Compare mypy's behavior with pyright using the provided Python 3.10 example. Done means the example type-checks without the reported override and variable-annotation errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100