[Python-checkins] peps: PEP 424: update from Alex.
georg.brandl
python-checkins at python.org
Sat Oct 6 13:00:10 CEST 2012
http://hg.python.org/peps/rev/aba3d25cbcaa
changeset: 4544:aba3d25cbcaa
user: Georg Brandl <georg at python.org>
date: Sat Oct 06 13:01:10 2012 +0200
summary:
PEP 424: update from Alex.
files:
pep-0424.txt | 26 +++++++++++---------------
1 files changed, 11 insertions(+), 15 deletions(-)
diff --git a/pep-0424.txt b/pep-0424.txt
--- a/pep-0424.txt
+++ b/pep-0424.txt
@@ -27,7 +27,7 @@
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 @@
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
--
Repository URL: http://hg.python.org/peps
More information about the Python-checkins
mailing list