Does the Python inbuilt library have an incrementable counter?

Question:

Is there anything like this in the Python inbuilt library:

class Counter:
    def __init__(self, start=0):
        self.val = start

    def consume(self):
        val = self.val
        self.val += 1
        return val

I see this as much safer way of implementing code where a counter needs to be used and then immediately incremented on the next line. Kind of like using i++ in other languages. But I’m trying to avoid clogging up my library with definitions like this if there’s an inbuilt method.

Asked By: Alexander Soare

||

Answers:

You have basically reimplemented itertools.count, with consume standing in for __next__. (__next__ is not typically called directly, but by passing the instance of count to the next function.)

>>> from itertools import count
>>> c = count()
>>> next(c)
0
>>> next(c)
1
>>> next(c)
2
Answered By: chepner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.