简体   繁体   English

从settings.py导入的变量的UnboundLocalError

[英]UnboundLocalError for variable imported from settings.py

I have a file settings.py which has the following variables defined: 我有一个文件settings.py,其中定义了以下变量:

DEBUG_MODE = True
WRAP_UP = False

I am importing settings into my script using: 我正在使用以下命令将设置导入到脚本中:

from settings import *

I am able to run this without any problem: 我可以毫无问题地运行它:

if(DEBUG_MODE):
    # Do something

But when I run this: 但是当我运行这个:

if(WRAP_UP == False):
    # Do something

it gives me the following error: 它给了我以下错误:

UnboundLocalError: local variable 'WRAP_UP' referenced before assignment.

Why does one variable work and the other doesn't? 为什么一个变量起作用而另一个变量不起作用? How do I fix this? 我该如何解决?

In Python, inside a function, any variables you don't explicitly declare global or nonlocal (closure) are considered local if you assign to them anywhere in the function, non-local (closure, global, or builtin) if you don't. 在Python中,在函数内部,如果您在函数中的任何位置分配了未明确声明的global变量或非nonlocal变量(闭包)的变量,则将其视为局部变量;如果未分配给变量,则将其视为nonlocal变量(闭包的,全局变量或内置变量) 。

So, assuming you do the from settings import * globally (if not, you have bigger problems…), that creates global variables named DEBUG_MODE and WRAP_UP , so you can do this: 因此,假设您from settings import *全局from settings import * (如果不是,则问题更大……),这将创建名为DEBUG_MODEWRAP_UP全局变量,因此您可以执行以下操作:

def spam():
    if DEBUG_MODE:
        # Do something

… and that works. ……而且行得通。 But if you do this: 但是,如果您这样做:

def eggs():
    if WRAP_UP:
        # Do something
    WRAP_UP = True

… that won't work. ……那是行不通的。 The assignment means that eggs has a local variable named WRAP_UP , which hides the global variable of the same name. 赋值意味着eggs具有一个名为WRAP_UP的局部变量,该局部变量隐藏了相同名称的全局变量。 So, the first line is trying to access that local variable, which doesn't have a value yet. 因此,第一行正在尝试访问该本地变量,该变量尚无值。

The solution is an explicit global statement, which will force eggs to use the global variable even though it has an assignment: 该解决方案是一个显式的global语句,即使有赋值,它也会强制eggs使用全局变量:

def eggs():
    global WRAP_UP
    if WRAP_UP:
        # Do something
    WRAP_UP = True

Of course that's assuming that you want eggs to reassign the global, but I suspect that's what you want. 当然,这是假设您希望 eggs重新分配全局对象,但是我怀疑那是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM