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

Brett Cannon brett at python.org
Mon Jul 16 15:01:14 CEST 2012


On Mon, Jul 16, 2012 at 3:36 AM, Stefan Behnel <stefan_ml at behnel.de> wrote:

> Alex Gaynor, 15.07.2012 00:11:
> > CPython currently defines an ``__length_hint__`` method on several
> types, such
> > as various iterators. This method is then used by various other
> functions (such
> > as ``map``) to presize lists based on the estimated returned by
> > ``__length_hint__``. Types can then define ``__length_hint__`` which are
> not
> > sized, and thus should not define ``__len__``, but can estimate or
> compute a
> > size (such as many iterators).
> >
> > Proposal
> > ========
> >
> > This PEP proposes formally documenting ``__length_hint__`` for other
> > interpreter and non-standard library Python to implement.
> >
> > ``__length_hint__`` must return an integer, 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. It may raise a ``TypeError`` if a specific instance
> cannot have
> > its length estimated. It may not return a negative value.
>
> I'd like to more visibly repeat my suggestion to make this a slot method
> "tp_length_hint()" in extension types that returns a Py_ssize_t.
>
> That suggests that a negative return value would have a special meaning
> instead of relying on return values like NotImplemented. The Python wrapper
> of that slot method could still implement a mapping for this.
>
> Return values could be -1 for "don't know" and -2 for "infinite" at the C
> level, and NotImplemented for "don't know" at the Python level. Not sure
> about a good Python value for "infinite".
>

Gods no. Making the return value different in C vs. Python code is just
asking for trouble in terms of having to remember that specific difference
while coding. Plus asking for people to check for an explicit negative
values instead of just >= 0 would be problematic and prone to error.


>
> Maybe return -1 for "infinite" at both levels and -2/NotImplemented for
> "don't know" in C/Python? That would suggest -3 to propagate exceptions at
> the C level.
>

See above.

This is another reason why I don't think the infinite iterator concept is
worth expressin. It's just mucking things up for no good reason. "infinite"
== "I don't know" in the case of pre-allocation of a list. Just raise an
exception or return None and be done with it. Nice and simple. And my vote
is for an exception as EAFP.

-Brett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20120716/ce8d0025/attachment.html>


More information about the Python-Dev mailing list