简体   繁体   中英

Python not recognizing global variables

I have a module I've been using for some time with global variables initialized outside of a function, such as:

myVar = 1

def fnPrintMyVar():
    print myVar

Today I was debugging and the interpreter suddenly stopped recognizing the global variables, yielding the familiar, NameError: global name 'myVar' is not defined in the console.

I ran it in WingIDE and stopped the code just before the print line. The IDE showed myVar correctly in the watch list, but when I tried to run the print line it raised the same exception.

As a temporary workaround, I put all my globals inside another function as below:

def fnVarHolder():
    global myVar
    myVar = 1

def fnPrintMyVar():
    global myVar
    print myVar

This worked for a while, then stopped working in the same way as suddenly as the first method. I have tried closing down everything, including resetting the system, but the exception is still raised. I assume there's a non-volatile file somewhere causing this, but I have no idea where to look. Any ideas would be much appreciated.

As for "non-volatile files somewhere" try deleting directories called __pycache__ and any *.pyo and *.pyc files.

Hope this helps, but since this sounds like a problem that is local to your computer it's hard to reproduce.

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