[Python-Dev] PEP 0424: A method for exposing a length hint
Nick Coghlan
ncoghlan at gmail.com
Sun Jul 15 10:47:38 CEST 2012
On Sun, Jul 15, 2012 at 6:21 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I suggest:
>
> * object (and hence all other types that don't explicitly override it)
> should have a __length_hint__ that raises TypeError;
We can keep it simpler than that just by changing the order of the checks.
> * __length_hint__ should be allowed to return None to indicate "don't know"
> or -1 to indicate "infinite".
>
> Presumably anything that wishes to create a list or other sequence from an
> object with a hint of -1 could then raise an exception immediately.
I'm not seeing the value in returning None over 0 for the don't know
case - it just makes the API harder to use. Declaring negative results
as meaning "I'm infinite" sounds reasonable, though:
def length_hint(obj):
"""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 underestimate by an arbitrary amount.
"""
try:
get_hint = obj.__length_hint__
except AttributeError:
return len(obj)
hint = get_hint()
if not isinstance(hint, int):
msg = "Length hint must be an integer, not %r"
raise TypeError(msg % type(hint))
if hint < 0:
raise ValueError("%r is an infinite iterator" % (obj,))
return hint
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev
mailing list