How to access global variables from a thread in Python
<p>Consider the following code: </p>

<pre><code>from threading import Thread 

def main():
    number = 5

    class my_thread(Thread):
        def __init__(self, range):
            Thread.__init__(self)
            self.range = range

        def run(self):
            global number
            for i in self.range:
                number += 1

    t1 = my_thread(range(4))
    t1.start()
    t1.join()
    print number

main()
</code></pre>

<p>The output from this program is </p>

<pre><code>Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Tools\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Dev\Workspace\Hello World\Hello.py", line 14, in run
    number += 1
NameError: global name 'number' is not defined

5
</code></pre>

<p>Evidently, <code>my_thread</code> does not have access to <code>number</code>. Why is this, and how can I access it correctly? </p>