Leon palafox
Leon palafox

Reputation: 2785

Suggestions to implement an automatic counter in Python

In Tex, we have the count variables that get automatically updated each time there is a call to reference, that way the figure counter goes up automatically.

I wanted to do something similar in python for counters, for example, each time I need the counter it already has the new value without me needing to add

A+=1

Thanks

Upvotes: 3

Views: 1986

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Use itertools.count(), this is an iterator so use the next() function the advance the object to the next value:

from itertools import count

yourcounter = count()

next_counted_value = next(yourcounter)

You can create a lambda to wrap the function:

yourcounter = lambda c=count(): next(c)

Or use a functools.partial() object:

from functools import partial

yourcounter = partial(next, count())

Then call the object each time:

next_counted_value = yourcounter()

Upvotes: 4

Related Questions