If you know the input is sizeable, why not check its length instead of the
map's?

On Mon, Nov 26, 2018, 1:35 PM Kale Kundert <k...@thekunderts.net wrote:

> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to