Search code examples
pythonpython-multithreadingthreadpoolexecutor

UnboundLocalError: local variable referenced before assignment in Python


so i faced strange behaviour with this code below. I am getting error that local variable flag is referenced before assignment, but its assigned at the top as global variable. Can someone tell me whats going here and why flag is not incrementing as expected?

import concurrent.futures


flag = 0
def make_some():
    try:
        flag += 1
    except Exception as e:
        print(e)

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
    tasks = {
        executor.submit(
            make_some
        ): task_id
        for task_id in [1,2,3]
    }
    for future in concurrent.futures.as_completed(tasks):
        pass

Solution

  • you have to use global keyword to solve this problem

    read more here https://www.tutorialspoint.com/global-keyword-in-python

    so without global , every variable is only in the local scope as if there was no global variable defined and hence the error

    once you use the global keyword, then in the inner scope python acknowledges the presence of a global variable definition