PEP 424 – 暴露长度提示的方法
- 作者:
- Alex Gaynor <alex.gaynor at gmail.com>
- 状态:
- 最终
- 类型:
- 标准轨道
- 创建:
- 2012-07-14
- Python 版本:
- 3.4
- 历史记录:
- 2012-07-15
摘要
CPython 目前在几种类型上定义了 __length_hint__
方法,例如各种迭代器。然后,该方法由各种其他函数(例如 list
)使用,以根据 __length_hint__
返回的估计值预先调整列表大小。未进行大小调整的类型(因此不应定义 __len__
)可以定义 __length_hint__
,以允许估计或计算大小(例如许多迭代器)。
规范
此 PEP 正式记录了 __length_hint__
,供其他解释器和非标准库 Python 模块实现。
__length_hint__
必须返回一个整数(否则会引发 TypeError
)或 NotImplemented
,并且不需要准确。它可以返回的值可能大于或小于容器的实际大小。返回值 NotImplemented
表示没有有限的长度估计值。它不能返回负值(否则会引发 ValueError)。
此外,还添加了一个新函数 operator.length_hint
提示,具有以下语义(定义了如何使用 __length_hint__
)
def length_hint(obj, default=0):
"""Return an estimate of the number of items in obj.
This is useful for presizing containers when building from an
iterable.
If the object supports len(), the result will be
exact. Otherwise, it may over- or under-estimate by an
arbitrary amount. The result will be an integer >= 0.
"""
try:
return len(obj)
except TypeError:
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return default
try:
hint = get_hint(obj)
except TypeError:
return default
if hint is NotImplemented:
return default
if not isinstance(hint, int):
raise TypeError("Length hint must be an integer, not %r" %
type(hint))
if hint < 0:
raise ValueError("__length_hint__() should return >= 0")
return hint
基本原理
能够根据 __length_hint__
估计的预期大小预先分配列表,可能是一项重大优化。据观察,CPython 运行某些代码的速度比 PyPy 快,这仅仅是因为存在此优化。
版权
本文档已进入公有领域。
来源: https://github.com/python/peps/blob/main/peps/pep-0424.rst
上次修改: 2023-09-09 17:39:29 GMT