[Python-ideas] Suggested MapView object (Re: __len__() for map())

Terry Reedy tjreedy at udel.edu
Tue Dec 11 12:51:17 EST 2018

On 12/1/2018 8:07 PM, Greg Ewing wrote:
> Steven D'Aprano wrote:

After defining a separate iterable mapview sequence class

>> For backwards compatibilty reasons, we can't just make map() work like 
>> this, because that's a change in behaviour.
> Actually, I think it's possible to get the best of both worlds.

I presume you mean the '(iterable) sequence' 'iterator' worlds.  I don't 
think they should be mixed.  A sequence is reiterable, an iterator is 
once through and done.

> Consider this:
> from operator import itemgetter
> class MapView:
>      def __init__(self, func, *args):
>          self.func = func
>          self.args = args
>          self.iterator = None
>      def __len__(self):
>          return min(map(len, self.args))
>      def __getitem__(self, i):
>          return self.func(*list(map(itemgetter(i), self.args)))
>      def __iter__(self):
>          return self
>      def __next__(self):
>          if not self.iterator:
>              self.iterator = map(self.func, *self.args)
>          return next(self.iterator)

The last two (unnecessarily) restrict this to being a once through 
iterator.  I think much better would be

     def __iter__: return map(self.func, *self.args)

Terry Jan Reedy

More information about the Python-ideas mailing list