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 my understanding is correct, to eliminate the <code>global</code> counter you could create a closure for you variable and return a function that increments it. </p>

<p>The original function <code>counter</code> is called only once, consecutive calls simply increment the counter:</p>

<pre><code>def count(n):
    c = n
    def incr():
        nonlocal c
        c += 1
        print(c)
        return c
    return incr
</code></pre>

<p><code>count</code> is initialized with some state <code>n</code> and <code>incr</code> references that state in consecutive calls:</p>

<pre><code>&gt;&gt;&gt; f = count(2)
&gt;&gt;&gt; f()
3
&gt;&gt;&gt; f()
4
&gt;&gt;&gt; f()
5
</code></pre>

python python-3.x generator counter