[Python-ideas] __len__() for map()

Kale Kundert kale at thekunderts.net
Mon Nov 26 20:37:11 EST 2018


Hi Steven,

Thanks for the good feedback.

> First, the usefulness: we still have to wrap the call to 
> len() in a try...except block, even if we know we have a map object, 
> because we won't know whether the underlying iterable supports len. So 
> it won't reduce the amount of code we have to write. At best it will 
> allow us to take a fast-path when len() returns a value, and a slow-path 
> when it raises.

I think most of the time you would know whether the underlying iterable was
sized or not.  After all, if you need the length, whatever code you're writing
would probably not work on an infinite/unsized iterable.

> So the length of the iterable has to vary as you iterate over it, or you 
> break the invariant shown above.

I think I see the problem here.  map() is an iterator, where I was thinking of
it as a wrapper around an iterable.  Since an iterator is really just a pointer
into an iterable, it doesn't really make sense for it to have a length.  Give it
one, and you end up with the inconsistencies you describe.

I guess I probably would have disagreed with the decision to make map() an
iterator rather than a wrapper around an iterable.  Such a prominent function
should have an API geared towards usability, not towards implementing a
low-level protocol (in my opinion).  But clearly that ship has sailed.

-Kale




More information about the Python-ideas mailing list