Shouldn't the return type of `__reversed__` be an `Iterable[T]` instead of `Iterator[T]`?

未关闭
#13,218 8 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
35/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
tooling

调研方向

先从链接行中的 stdlib/typing.pyi 里的 Reversible 定义开始,然后比较 issue 中的两个 mypy Playground 示例。确定一个既能接受所示 reversed 实现、又能保持 reversed(my_iter) 类型检查的签名;当两个报告的错误都得到解决,且没有削弱无关的类型行为时,即视为完成。

由索引模型根据 Issue 内容生成。

描述

Currently the return type of Reversible.__reversed__ is typed as Iterator[T], which suggests that the returned instance must have both an __next__ and an __iter__ method.

https://github.com/python/typeshed/blob/0e9c9e1362959512a880abbf1275471b0d76924f/stdlib/typing.pyi#L446-L448

However, the following code seems to work fine at runtime:

from dataclasses import dataclass
from typing import Iterator, Iterable

@dataclass
class MyIter:
    _values: list[int]
    
    def __iter__(self) -> Iterator[int]:
        return iter(self._values)
    
    def __reversed__(self) -> Iterator[int]:
        return MyIter(self._values[::-1])

my_iter = MyIter([1, 2, 3])
for x in my_iter:
    print(x)
for x in reversed(my_iter):
    print(x)

Note that __reversed__ here returns a MyIter instance, which has an __iter__ method, but no __next__, i.e., it is an Iterable but not an Iterator. The Python interpreter seems to deal with that fine at runtime, i.e., it doesn't actually seem to need the __next__ method. This is slightly surprising, because the docs specify:

It should return a new iterator object that iterates over all the objects in the container in reverse order.

I.e., it doesn't use the word "iterable object".

Unfortunately, the current signature of __reversed__ means that this example does not type check: Obviously the type checker has to complain about the return MyIter(...) line, because MyIter is indeed only an Iterable (example on mypy playground):

main.py:13: error: Incompatible return value type (got "MyIter", expected "Iterator[int]")  [return-value]
main.py:13: note: "MyIter" is missing following "Iterator" protocol member:
main.py:13: note:     __next__
Found 1 error in 1 file (checked 1 source file)

Now I'm wondering if the signature should actually be def __reversed__(self) -> Iterable[int] to lessen the requirement and match the runtime behavior?

Note that simply changing the return type to Iterable on user side means that the return statement now type checks, but then all usages (reversed(my_iter)) stop to type check because the type checker will no longer consider MyIter as a valid Reversible (modified example on mypy playground):

main.py:18: error: No overload variant of "reversed" matches argument type "MyIter"  [call-overload]
main.py:18: note: Possible overload variants:
main.py:18: note:     def [_T] __new__(cls, Reversible[_T], /) -> reversed[_T]
main.py:18: note:     def [_T] __new__(cls, SupportsLenAndGetItem[_T], /) -> reversed[_T]
Found 1 error in 1 file (checked 1 source file)
主要语言
Python
星标
5.1k
派生
2.1k
平均合并
1 天 13 小时
30 天内合并 PR
73

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/typeshed 的其他 Issue

查看 python/typeshed 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。