[Python-ideas] Allow __len__ to return infinity

Andrew Barnert abarnert at yahoo.com
Wed Feb 26 21:16:45 CET 2014


I think my original reply got swallowed by Google Groups again, so apologies if this is a repeat to some or all…

From: Ram Rachum <ram.rachum at gmail.com>
Sent: Tuesday, February 25, 2014 2:02 AM


>I'd like to have some objects that return infinity from their __len__ method. Unfortunately the __len__ method may only return an int, and it's impossible to represent an infinity as an int. Do you think that Python could allow returning infinity from __len__?


What code do you have that needs to distinguish between actually infinite iterables and potentially infinite ones?

Presumably you still want iterators to raise a TypeError rather than try to guess, so as soon as you pass an infinite iterable through a genexpr or itertools function it's going to turn into a length-less iterable.

Are you looking for this as a sort of intermediate step from length-less iterables to the kind of lazy lists that some functional languages have? You actually can build a lazy list (implementing Sequence by storing a list of already-seen-prefix and an iterator of not-yet-seen values) pretty easily (and write a lazytools module full of functions like the relevant itertools functions). I did this a few years back, but never found a good use for it and abandoned it. 

Anyway, if so, a lazy list that doesn't know its length already needs to say so by raising an exception from __len__, and a lazy list that knows its length is infinite can do the same thing, and I couldn't think of any uses cases where that would be a problem, even though I expected there would be some. So, if you have one, I'd love to hear it.



More information about the Python-ideas mailing list