it occurs to me that Python generators not impleme...
# random
w
it occurs to me that Python generators not implementing
len
(even optionally) is a bummer from an allocation perspective, because
list
and
tuple
don’t know how large a collection to allocate to consume a generator.
if generators implemented optional
len
, you could imagine that a generator comprehension like
Copy code
len(x for x in y)
…would delegate to
len(y)
(and so on, if
y
was also a generator)
you’d have to disable that delegation if there were any filters/conditionals on the generator, but at least sometimes…
(i might be complaining about
iterators
rather than `generators`… but you get the idea)
f
Copy code
>>> xs = [1,2,3]
>>> i = iter(xs)
>>> i.__length_hint__()
3
w
Oh hi! Thanks.
f
I only just found it as a result of searching after seeing your question.
Very good idea => someone must have at least proposed in a PEP
w
having said that:
Copy code
>>> (x for x in range(10)).__length_hint__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute '__length_hint__'
>>> range(10).__length_hint__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'range' object has no attribute '__length_hint__'
>>> (x for x in [1, 2]).__length_hint__()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'generator' object has no attribute '__length_hint__'
f
maybe use the
length_hint
function from the PEP? (which tries to call
len
first)
I'm thinking they do it that way if `__len`__ and
__length_hint__
are not implemented together