[Python-Dev] PEP 0424: A method for exposing a length hint

Steven D'Aprano steve at pearwood.info
Sun Jul 15 10:21:13 CEST 2012


Nick Coghlan wrote:
> On Sun, Jul 15, 2012 at 9:18 AM, Benjamin Peterson <benjamin at python.org> wrote:
>>> Open questions
>>> ==============
>>>
>>> There are two open questions for this PEP:
>>>
>>> * Should ``list`` expose a kwarg in it's constructor for supplying a length
>>>   hint.
>>> * Should a function be added either to ``builtins`` or some other module which
>>>   calls ``__length_hint__``, like ``builtins.len`` calls ``__len__``.
>> Let's try to keep this as limited as possible for a public API.
> 
> Length hints are very useful for *any* container implementation,
> whether those containers are in the standard library or not. Just as
> we exposed operator.index when __index__ was added, we should expose
> an "operator.length_hint" function with the following semantics:
[...]

As given, length_hint gives no way of distinguishing between iterables and 
non-iterables:

py> length_hint([])
0
py> length_hint(42)
0

nor does it give iterable objects a way to indicate that either they don't 
know their length, or that they are infinite.

I suggest:

* object (and hence all other types that don't explicitly override it)
   should have a __length_hint__ that raises TypeError;

* __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.




-- 
Steven


More information about the Python-Dev mailing list