[Python-ideas] Allow __len__ to return infinity

Paul Moore p.f.moore at gmail.com
Tue Feb 25 12:46:26 CET 2014


On 25 February 2014 11:18, Steven D'Aprano <steve at pearwood.info> wrote:
> (1) __len__ can return *any* float, regardless of value, including
> lengths of 0.5, NAN, 1e300, etc. This is undesirable because lengths of
> sequences should be positive or zero whole numbers, not arbitrary
> floating point values like 4.5.
>
> (2) __len__ cannot return any float, but only INF. Which means that the
> condition that len() only returns ints will be broken in the most
> surprising way, with a single exception.

Either of these would break range(len(x)) at a minimum, and probably
most other code that uses len(). So you'd be left with code having to
identify "objects that only return finite len" and "objects that could
have one of the new len values". And if the OP can detect that, he can
just do so in his code and special case his objects, rather than
changing the len protocol.

Paul


More information about the Python-ideas mailing list