[Python-ideas] __len__() for map()
Kale Kundert
kale at thekunderts.net
Mon Nov 26 16:29:21 EST 2018
I just ran into the following behavior, and found it surprising:
>>> len(map(float, [1,2,3]))
TypeError: object of type 'map' has no len()
I understand that map() could be given an infinite sequence and therefore might
not always have a length. But in this case, it seems like map() should've known
that its length was 3. I also understand that I can just call list() on the
whole thing and get a list, but the nice thing about map() is that it doesn't
copy data, so it's unfortunate to lose that advantage for no particular reason.
My proposal is to delegate map.__len__() to the underlying iterable. Similarly,
map.__getitem__() could be implemented if the underlying iterable supports item
access:
class map:
def __init__(self, func, iterable):
self.func = func
self.iterable = iterable
def __iter__(self):
yield from (self.func(x) for x in self.iterable)
def __len__(self):
return len(self.iterable)
def __getitem__(self, key):
return self.func(self.iterable[key])
Let me know if there any downsides to this that I'm not seeing. From my
perspective, it seems like there would be only a number of (small) advantages:
- Less surprising
- Avoid some unnecessary copies
- Backwards compatible
-Kale
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181126/242f4b80/attachment.html>
More information about the Python-ideas
mailing list