简体   繁体   中英

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. And also I don't know why it doesn't print else: block print statement.

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

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

>>> ===== 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

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. 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.

As an example for a scenario where you would need to use global in order to expose a variable in another scope:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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