Search code examples
pythonpython-itertools

Equality of itertools.count in Python


Consider the interactive Python code:

>>> from itertools import count
>>> count(0) == count(0)
False

Why is equality not implemented here and defaults to identity? Is this intentional or merely an oversight?

Edit: I did not make myself clear enough. I expected equality to be expressed as the equality of starting points unaware that the current state of the iterator is also being tracked by the count object, as pointed out by Martijn Pieters in the comments.


Solution

  • To wrap up the helpful comments given by Martijn Pieters and J. F. Sebastian to my question and to close this thereby: itertools.count is designed as an iterator and thus tracks its current iteration state. Thereby it is not obvious how equality should be defined.

    I wound up wrapping count in the following manner to achieve the behaviour I had expected:

    import itertools
    
    class count(object):
    
        def __init__(self, start=0, step=1):
            self.start = start
            self.step = step
    
        def __eq__(self, other):
            return self.start == other.start and self.step == other.step
    
        def __iter__(self):
            return itertools.count(self.start, self.step)