容器总是可迭代的吗?

Are containers always iterable?

根据这张图,是否存在容器不可迭代的场景?

取决于您所说的总是是什么意思。根据collections.abc

  • 一个容器是一个实现了__contains__方法的对象
  • 可迭代对象是实现 __iter__(或 __getitem__ 作为后备)的对象

因此,理论上,不,您可以实现一个不可迭代的容器。但是,所有标准 python 容器(以及库实现的大多数容器)也是可迭代的。

容器所做的只是为您提供 if x in yif x not in y 语法。

你可能有一个 Range(min: float, max: float) 实现 __contains__ 作为范围内任何数字返回 True,这将允许你写 if 3.14 not in provided_range 等。那不会是可迭代。

图表有点误导,暗示 {list, set, dict} comprehension 是生产容器的唯一有趣的东西。