0

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
Henri
  • 3
  • 1
  • 2

2 Answers2

1

This should work (adding global):

import concurrent.futures


flag = 0
def make_some():

    global flag  # <--- USE GLOBAL

    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
Marcin
  • 215,873
  • 14
  • 235
  • 294
-2

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

ashish singh
  • 6,526
  • 2
  • 15
  • 35
  • 1
    The `global` is required only for re-assigning a global variable inside a inner scope. You can always read a global variable from inner scope if non of the local variables have a clashing name (which is what's happening here) – rdas May 22 '20 at 04:49