(original) (raw)
On Sat, Jul 14, 2012 at 10:16 PM, Nick Coghlan <ncoghlan@gmail.com> wrote:
On Sun, Jul 15, 2012 at 9:18 AM, Benjamin Peterson <benjamin@python.org> wrote:Length hints are very useful for \*any\* container implementation,
>> 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.
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:
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. The
result will be an integer >= 0.
"""
try:
return len(obj)
except TypeError:
try:
get\_hint = obj.\_\_length\_hint\_\_
except AttributeError:
return 0
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)
return hint
There's no reason to make pure Python container implementations
reimplement all that for themselves.
Cheers,
Nick.
\--
Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
Sounds reasonable to me, the only issue with your psuedocode (err... I mean Python ;)), is that there's no way for the \_\_lenght\_hint\_\_ to specify that that particular instance can't have a length hint computed. e.g. imagine some sort of lazy stream that cached itself, and only wanted to offer a length hint if it had already been evaluated. Without an exception to raise, it has to return whatever the magic value for length\_hint is (in your impl it appears to be 0, the current \_PyObject\_LengthHint method in CPython has a required \`default\` parameter). The PEP proposes using TypeError for that.
Anyways that code looks good, do you want to add it to the PEP?
Alex
--
"I disapprove of what you say, but I will defend to the death your right to say it." -- Evelyn Beatrice Hall (summarizing Voltaire)
"The people's good is the highest law." -- Cicero
"I disapprove of what you say, but I will defend to the death your right to say it." -- Evelyn Beatrice Hall (summarizing Voltaire)
"The people's good is the highest law." -- Cicero