UnboundLocalError: local variable referenced before assignment in Python

UnboundLocalError: local variable referenced before assignment in Python

所以我遇到了下面这段代码的奇怪行为。我收到错误消息,局部变量 flag 在赋值前被引用,但它作为全局变量在顶部被赋值。有人能告诉我这里发生了什么以及为什么 flag 没有按预期递增吗?

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

你必须使用 global 关键字来解决这个问题

在此处阅读更多内容 https://www.tutorialspoint.com/global-keyword-in-python

所以没有 global ,每个变量都只在本地范围内,就好像没有定义全局变量一样,因此出现错误

一旦您使用 global 关键字,那么在内部作用域中 python 确认存在 global 变量定义

这应该有效(添加 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