title: Python: Elegant way to increment a global variable
body: <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>