[Python-ideas] Make len() usable on a generator

Terry Reedy tjreedy at udel.edu
Sun Oct 12 07:38:53 CEST 2014


On 10/12/2014 12:24 AM, 
random832 at fastmail.us wrote:
> On Sat, Oct 11, 2014, at 01:11, Steven D'Aprano wrote:
>> It might be nice if some generators will be processed by the "known
>> length" branch, but it doesn't save you from having to write the
>> "unknown length" branch.
>
> You don't have to if you don't want to. Demanding that your callers pass
> in an object on which __len__ is defined is no different than demanding
> objects with any other method defined. That's how duck typing works.

Iterators, including generators, can optionally have a __length_hint__ 
method, which can be used by list, etc, for better initial space allocation.

"object.__length_hint__(self)

     Called to implement operator.length_hint(). Should return an 
estimated length for the object (which may be greater or less than the 
actual length). The length must be an integer >= 0. This method is 
purely an optimization and is never required for correctness."

I believe this was added when Raymond H. noticed that some of the 
itertools generators could sometimes give accurate length information. 
Guido did not want to add __len__, just sometimes, lest it incorrectly 
become regarded as part of the iterator protocol.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list