PEP 424 – 一种暴露长度提示的方法
- 作者:
- Alex Gaynor <alex.gaynor at gmail.com>
- 状态:
- 最终版
- 类型:
- 标准跟踪
- 创建日期:
- 2012年7月14日
- Python 版本:
- 3.4
- 发布历史:
- 2012年7月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