witty-crayon-22786
09/22/2023, 8:55 PMlen (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.witty-crayon-22786
09/22/2023, 8:57 PMlen, you could imagine that a generator comprehension like
len(x for x in y)
…would delegate to len(y) (and so on, if y was also a generator)witty-crayon-22786
09/22/2023, 8:57 PMwitty-crayon-22786
09/22/2023, 8:58 PMiterators rather than `generators`… but you get the idea)fast-nail-55400
09/22/2023, 9:04 PM__length_hint__ https://peps.python.org/pep-0424/fast-nail-55400
09/22/2023, 9:05 PM>>> xs = [1,2,3]
>>> i = iter(xs)
>>> i.__length_hint__()
3witty-crayon-22786
09/22/2023, 9:06 PMfast-nail-55400
09/22/2023, 9:06 PMfast-nail-55400
09/22/2023, 9:06 PMwitty-crayon-22786
09/22/2023, 9:41 PM>>> (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__'fast-nail-55400
09/22/2023, 9:51 PMlength_hint function from the PEP? (which tries to call len first)fast-nail-55400
09/22/2023, 9:52 PM__length_hint__ are not implemented together