Home > Net >  Does the Python built-in library have an incrementable counter?
Does the Python built-in library have an incrementable counter?

Time:12-21

Is there anything like this in the Python built-in 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.

CodePudding user response:

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
  • Related