Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does the Python inbuilt library have an incrementable counter?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading