PEP 424: update from Alex.
This commit is contained in:
parent
995ee35299
commit
d990294a02
26
pep-0424.txt
26
pep-0424.txt
|
@ -27,7 +27,7 @@ Specification
|
|||
This PEP formally documents ``__length_hint__`` for other
|
||||
interpreters and non-standard-library Python modules to implement.
|
||||
|
||||
``__length_hint__`` must return an integer (else a TypeError is raised) or
|
||||
``__length_hint__`` must return an integer (else a ``TypeError`` is raised) or
|
||||
``NotImplemented``, and is not required to be accurate. It may return a value
|
||||
that is either larger or smaller than the actual size of the container. A
|
||||
return value of ``NotImplemented`` indicates that there is no finite length
|
||||
|
@ -47,29 +47,25 @@ be used)::
|
|||
exact. Otherwise, it may over- or under-estimate by an
|
||||
arbitrary amount. The result will be an integer >= 0.
|
||||
"""
|
||||
if <obj has a __len__ method>:
|
||||
try:
|
||||
return len(obj)
|
||||
else:
|
||||
except TypeError:
|
||||
try:
|
||||
get_hint = obj.__length_hint__
|
||||
get_hint = type(obj).__length_hint__
|
||||
except AttributeError:
|
||||
return default
|
||||
hint = get_hint()
|
||||
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))
|
||||
return max(hint, 0)
|
||||
|
||||
Note: there is no good way to spell "obj has a __len__ method" in pure
|
||||
Python. In CPython, this comes down to checking for a ``sq_length``
|
||||
slot. Other implementations presumably have their own way of
|
||||
checking. Calling ``len(obj)`` and catching TypeError is not quite
|
||||
correct (as it would assume no __len__ method exists when in fact one
|
||||
exists but calling it raises TypeError); checking ``hasattr(obj,
|
||||
'__len__')`` likewise is incorrect if obj is a class defining a
|
||||
``__len__`` method for its instances.
|
||||
if hint < 0:
|
||||
raise ValueError("__length_hint__() should return >= 0")
|
||||
return hint
|
||||
|
||||
|
||||
Rationale
|
||||
|
|
Loading…
Reference in New Issue