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>If you want to maintain state across multiple instances of <code>Count</code>, then use a variable in the class scope, and reference it with the <code>Count.</code> prefix, like this:</p>

<pre><code>class Count:
    curr = 0

    def __init__(self, startWith = None):
        if startWith is not None: Count.curr = startWith - 1

    def gen(self):
        while True:
            Count.curr += 1
            yield Count.curr
</code></pre>

<p>Note that if you want to maintain state, the constructor should allow for the possibility to <em>not</em> reset the counter, but leave it untouched.</p>

<p>As a side note, you might be interested in letting the generator generate a never ending series as shown above.</p>

<p>Here is how you could use the above class:</p>

<pre><code># Get generator that starts with 2
gen = Count(2).gen();

print (next(gen)); # -&gt; 2
print (next(gen)); # -&gt; 3
print (next(gen)); # -&gt; 4

# Get a generator that continues ...
gen2 = Count().gen();

print (next(gen2)); # -&gt; 5

# We can still use the previous generator also:

print (next(gen)); # -&gt; 6

# Start with 0:

gen3 = Count(0).gen();

print (next(gen3)); # -&gt; 0

# Other generators follow suit:

print (next(gen)); # -&gt; 1
print (next(gen2)); # -&gt; 2
</code></pre>

python python-3.x generator counter