[Python-Dev] PEP 0424: A method for exposing a length hint
ncoghlan at gmail.com
Sun Jul 15 07:16:02 CEST 2012
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
>> * 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:
"""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. The
result will be an integer >= 0.
get_hint = obj.__length_hint__
hint = get_hint()
if not isinstance(hint, int):
raise TypeError("Length hint must be an integer, not
%r" % type(hint))
if hint < 0:
raise ValueError("Length hint (%r) must be >= 0" % hint)
There's no reason to make pure Python container implementations
reimplement all that for themselves.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-Dev