简体   繁体   English

关于 Python 全局变量声明的警告

[英]Warning on Python global variable declaration

Is this can be ignored.这是可以忽略的。 I am getting warning as described below.我收到如下所述的警告。 How will my code succeed?我的代码将如何成功? I have to have this ignoreList variable in my program in global scope at whatever the cause.无论ignoreList何种原因,我都必须在全局范围内的程序中使用这个ignoreList变量。 And also I don't know why it doesn't print else: block print statement.而且我也不知道为什么它不打印else:块打印语句。

try:
    ignoreList
except NameError:
    global ignoreList
else:
    print 'If property of ignoreList is not set, then please adjust properties to be set for ignoreList'    

Here is the Warning while in the execution of program in python IDLE这是在python IDLE中执行程序时的警告

Warning (from warnings module): File "C:\\Users\\Sathasivam_Anand\\Documents\\ignore_list_check.py", line 4 global ignoreList SyntaxWarning: name 'ignoreList' is used prior to global declaration警告(来自警告模块):文件“C:\\Users\\Sathasivam_Anand\\Documents\\ignore_list_check.py”,第 4 行 global ignoreList SyntaxWarning:名称 'ignoreList' 在全局声明之前使用

>>> ===== RESTART: C:\\Users\\Sathasivam_Anand\\Documents\\ignore_list_check.py =====

Your code fragment doesn't make a lot of sense without more context.如果没有更多上下文,您的代码片段没有多大意义。 To get a better understanding of the keyword look at this: Use of “global” keyword in Python为了更好地理解关键字,请查看: 在 Python 中使用“全局”关键字

As for your code it makes the variable only available in a global scope after it errors which is unusual.至于您的代码,它使变量仅在发生错误后在全局范围内可用,这是不寻常的。 As the warning indicates you would/should define the variable ignoreList a global from the start to get rid of the error.正如警告所示,您将/应该从一开始ignoreList变量ignoreList定义为一个全局变量以消除错误。 The question would be why you would only expose it if the code runs into an error to begin with.问题是为什么你只在代码一开始就遇到错误时才公开它。

Furthermore if you didn't include it in some kind of function or other encapsulation the global keyword doesn't do anything int hat context.此外,如果您没有将它包含在某种函数或其他封装中,则global关键字不会执行任何 int hat 上下文。

As an example for a scenario where you would need to use global in order to expose a variable in another scope:作为您需要使用 global 以在另一个范围内公开变量的场景的示例:

def test():
    global a
    a = 10
    return 20
b = test()
print(a,b)

An example where it doesn't make sense as there is just a single scope to begin with:一个没有意义的例子,因为只有一个范围开始:

a = 10
global a
b = 20
print(a,b)

Your code fragment would indicate this case as you're missing additional indention.您的代码片段会指出这种情况,因为您缺少额外的缩进。 You might have omitted it purposely but by also omitting any information about the code that surrounds it (eg if it is placed within a function) you code doesn't make a lot of sense.您可能有意省略了它,但同时也省略了有关围绕它的代码的任何信息(例如,如果它被放置在一个函数中),您的代码就没有多大意义。

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

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