[Python-ideas] Expose `itertools.count.start` and implement `itertools.count.__eq__` based on it, like `range`.

Terry Reedy tjreedy at udel.edu
Fri May 16 00:51:57 CEST 2014


On 5/15/2014 4:02 PM, Ram Rachum wrote:
> I suggest exposing `itertools.count.start` and implementing
> `itertools.count.__eq__` based on it. This'll provide the same benefits
> that `range` got by exposing `range.start` and allowing `range.__eq__`.

The benefits cannot be the same because range and count are in different 
categories.

A range object is an immutable, constant attribute, reiterable sequence 
object. It makes sense to expose the read-only constants and compare on 
the basis of them. This is as sensible as comparing other sequences.

A count is an iterator.  We do not try to compare iterators (except by 
identity). The start value is only the initial value yielded. As soon as 
values are pulled from the iterator, the starting value is history. The 
generator equivalent in the doc can be condensed a bit to how I would 
actually write it.

def count(start=0, step=1):
     while True:
         yield start
         start += step

For an iterator class, I would save the start parameter as self.n, 
.count, or .current. In other words, something equivlaent to

     def __init__(self, start=0, step=1):
         self.count = start
         self.step = step

If you want an augmented iterator class, you should write one yourself 
for your specific needs.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list