Elegant way to increment a global variable in Python:
This is what I have so far:
my_i = -1
def get_next_i():
global my_i
my_i += 1
return my_i
with generator:
my_iter = iter(range(100000000))
def get_next_i():
return next(my_iter)
with class:
class MyI:
MyI.my_i = -1
@staticmethod
def next():
MyI.my_i += 1
return MyI.my_i
What would be the best alternative to those?
The purpose of these functions is to assign a unique number to a specific event in my code. The code is not just a single loop, so using
for i in range(...):
is not suitable here. A later version might use multiple indices assigned to different events. The first code would require duplication to solve such an issue. (get_next_i()
,get_next_j()
, ...)
Thank You.
As others suggested, itertools.count()
is the best option, e.g.
import itertools
global_counter1 = itertools.count()
global_counter2 = itertools.count()
# etc.
And then, when you need it, simply call next
:
def some_func():
next_id = next(global_counter1)
EDIT: Changed global_counter1.next()
(which worked only in Python 2) to next(global_counter1)
, which works also in Python 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With