git.net

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

Iterators, iterables and special objects


On 25/07/2020 06:35, Random832 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.


If the design calls for a single iteration of the contents of some 
container (for example), then need a signal to indicate 'end of data', 
ie StopIteration.

Conversely, if prepared to iterate continuously, don't ever want to see 
that exception.

How to differentiate?


Solution already available:
perhaps cycle() or chain()
itertools ? Functions creating iterators for efficient looping
https://docs.python.org/3/library/itertools.html
-- 
Regards =dn