can I have a global variable in python without declaring it as global?
<p>I want some sort of a global state that maintains the current number, as well as a function to generate the next number.</p>

<p>I can write a generator to give me the next number. </p>

<pre><code> def gen(self, n):
    yield n
    yield n + 1
</code></pre>

<p>but what is a clean way to maintain its state? I do not want to simply have a global variable. Is there a better way to do this? or is that my only option?</p>

<p>I tried to make a class like this:</p>

<pre><code>class Count:
"""
Represents the counter which
generates variables
"""

def __init__(self, curr=0):
    """
    :param curr: the current integer
    """
    self.curr = curr

def gen(self):
    """
    A generator for the next
    number
    :return: generator
    """
    self.curr += 1
    yield self.curr
    yield self.curr + 1
</code></pre>

<p>but this will not work, because every time I create Count(), it will reset my counter which I don't want. </p>

<p>Or you can use the next(generator) function.</p>

<pre><code>def num_gen():
    n=1
    while n:
        yield n
        n += 1
</code></pre>

<p>Then</p>

<pre><code>&gt;&gt;my_gen = num_gen()
&gt;&gt;next(my_gen)
1
&gt;&gt;next(my_gen)
2
</code></pre>

<p>And so forth.  Whenever a generator yields a value, the state of the generator is stored so that it can resume execution later.</p>

python python-3.x generator counter