From d990294a0258f02b3009c10adaa3ef8f705ab56f Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sat, 6 Oct 2012 13:01:10 +0200 Subject: [PATCH] PEP 424: update from Alex. --- pep-0424.txt | 26 +++++++++++--------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/pep-0424.txt b/pep-0424.txt index 029bac9db..e0a873c98 100644 --- a/pep-0424.txt +++ b/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 : + 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