changing global variable with thread in Python
Question: I am trying to write a script updating a global variable every 10 seconds. For
simplicity let's just increment `q` once teach time

    
    
    import time, threading
    
    q = 0
    def f(q):
        # get asset position every 10 seconds:
        q += 1
        print q
    
        # call f() again in 10 seconds
        threading.Timer(10, f).start()
    
    
    # start calling f now and every 10 sec thereafter
    f(q)
    

Instead python says:

    
    
    UnboundLocalError: local variable 'q' referenced before assignment
    

What is the correct way to change the variable `q`?

* * *

this example uses threading, doesn't update any values. [Run certain code
every n seconds](http://stackoverflow.com/questions/3393612/run-certain-code-
every-n-seconds)


Answer: You need to explicitly declare q as a global. `q += 1` confuses the
interpreter otherwise.

    
    
    import threading
    
    q = 0
    def f():
        global q
        q += 1
        print q
        threading.Timer(10, f).start()
    
    f()
    

