[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Iterators, iterables and special objects

On Sat, Jul 25, 2020 at 4:37 AM Random832 <random832 at> wrote:
> On Tue, Jul 21, 2020, at 15:54, Terry Reedy wrote:
> > The transformers should be once-through iterators because they can be
> > passed once-through interators.  I suppose one could make them iterables
> > and add an attribute 'pristine' set to True in __init__ and False in
> > __iter__, but why have 2 objects instead of 1 when there is not gain in
> > function?
> Why not just allow them to be iterated multiple times, and the underlying iterator/iterable either handles that or doesn't as the case may be? We don't have a hard API distinction between iterables and iterators, all iterators are "iterable" in the sense that they have their own __iter__ method that returns self.
> i.e. the equivalent of
> class map:
>     def __init__(self, func, obj): ...
>     def __iter__(self): for x in iter(self.obj): yield self.func(x)
> That way if it is passed a once-through iterator, it is a once-through iterator with a couple extra steps, if passed an iterable it's an iterable.

And then someone will ask why you can't subscript a map object if the
underlying object could be subscripted, etc, etc, etc. It's not meant
to be a transparent layer over the object; it's just an iterator -
basically equivalent to:

def map(func, *iters):
        while True:
            yield func(*(next(i) for i in iters))
    except StopIteration:

If you want a "MappedList" class, or a "MappedDict" class, or
whatever, then build it - it isn't hard.