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
- The first one is long and I don't consider it as a better way to code .
- The second one is a bit more elegant, but have an upper limit.
- The third one is long, but at least have no global variable to work with.
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.