I followed a queue example from the bottom of the Python Queue page. I want to access some global variables within the worker function, however, some globals are accessible and some aren’t. In my simple example below, the ‘rows’ and ‘errors’ variables are accessible but then I get UnboundLocalError for count. If i put “global count” then it works. But I don’t understand why the other globals are accessible.
File "myfile.py", line 184, in dpn_worker
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
Here is the code example I used:
dpns = [1,2,3,4]
q = Queue.Queue()
rows = []
errors = []
count = 0
def dpn_worker():
while True:
item = q.get()
rows.append(1)
errors.append(1)
count += 1
q.task_done()
def main():
for d in dpns:
q.put(d)
for i in range(NUM_WORKERS):
t = threading.Thread(target=dpn_worker)
t.daemon = True
t.start()
q.join()
In this case, since count is an integer: –
is equivalent to
So, you are trying to modify the global variable, but are actually creating a local one.. But on the RHS, you are using the local variable before initialization..
Modify your dpn_worker as: –