Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Elegant way to increment a global variable

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.

like image 770
Szabolcs Dombi Avatar asked Sep 10 '16 08:09

Szabolcs Dombi


1 Answers

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.

like image 166
zvone Avatar answered Sep 27 '22 20:09

zvone