Python集合ValuesView abc:为什么它不继承Iterable?

Ala*_*oni 7 python collections abc

我刚刚在我的项目中检查了一些关于ABC的文档,我需要做一些类型相关的工作.这些是关于ValuesView类型的官方文档,在Python 2和3中:

https://docs.python.org/2/library/collections.html#collections.ValuesView https://docs.python.org/3/library/collections.abc.html

这是源代码(Python 2,但在Python 3中也是如此)

https://hg.python.org/releases/2.7.11/file/9213c70c67d2/Lib/_abcoll.py#l479

我对ValuesView接口感到非常困惑,因为从逻辑角度来看它应该继承自Iterable,恕我直言(它甚至得到了__iter__ Mixin方法); 相反,文档说它只是从MappingView继承而来,它继承自Sized,它不继承自Iterable.

所以我解雇了我的2.7翻译:

>>> from collections import Iterable
>>> d = {1:2, 3:4}
>>> isinstance(d.viewvalues(), Iterable) 
True
>>>
Run Code Online (Sandbox Code Playgroud)

毕竟,它看起来是可迭代的,因为Iterable自己的子类钩子.

但是我不明白为什么ValuesView没有明确的Iterable.其他ABC,如Sequence或Set,是明确可迭代的.这背后有一些神秘的原因,或者它只是一个文档+实现的缺点,一个很少使用的功能?

编辑:ValuesView从Python 3.7开始按预期工作.似乎只是疏忽.

Lem*_*nPy 5

在Python 3.7.2中,它继承自两者MappingView,而Collection后者又继承自(以及其他)Iterable。有人听你说话。

  • https://bugs.python.org/issue32467 “我继续这样做是因为它确实提供了一种整洁感(与 KeysView 和 ItemsView 相比),并且它可能会避免在某个地方出现迂腐的 StackOverflow 问题。” -> 事实上,这个问题已经被问过:-) (2认同)