Python: Elegant way to increment a global variable
<blockquote>
  <p>Elegant way to increment a global variable in Python:</p>
</blockquote>

<p>This is what I have so far:</p>

<pre><code>my_i = -1
def get_next_i():
    global my_i
    my_i += 1
    return my_i
</code></pre>

<p>with generator:</p>

<pre><code>my_iter = iter(range(100000000)) 
def get_next_i():
    return next(my_iter)
</code></pre>

<p>with class:</p>

<pre><code>class MyI:
    MyI.my_i = -1
    @staticmethod
    def next():
        MyI.my_i += 1
        return MyI.my_i
</code></pre>

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

<p><strong>What would be the best alternative to those?</strong></p>

<blockquote>
  <p>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 <code>for i in range(...):</code> 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. (<code>get_next_i()</code>, <code>get_next_j()</code>, ...)</p>
</blockquote>

<p>Thank You.</p>

<p>You can create a generator that has an infinite loop. Each call of <code>next(generator)</code> will return a next value, without limit. See <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python?rq=1">What does the &quot;yield&quot; keyword do in Python?</a> </p>

<pre><code>def create_generator()
    i=0
    while True:
        i+=1
        yield i

generator = create_generator()
print(next(generator))
print(next(generator))
</code></pre>

python python-3.x for-loop iterator generator