I have three python files in a project:
'''lib.py
library file that first defines and also accesses a boolean flag'''
vflag = False
...
def lib_method()
global vflag
if not vflag:
do_something_here
'''app.py
main application that sets the boolean flag defined in lib.py'''
import lib
lib.vflag = method_that_sets_or_resets_vflag()
'''processor.py
does some processing and needs to access the bool flag'''
from lib import *
...
def processor_method()
global vflag
...
if vflag:
do_something_here
I am able to set/ reset the flag at app.py, but processor method is not able to get the correct value for this boolean variable.
It only gets whatever is set at the beginning of lib.py(not what is set by app.py). The requirement is to access the value set at runtime by app.py, NOT the value to which it was initialized by lib.py
I am importing the lib file in different ways at app.py and processor.py. Does that make a difference ?
It may be a fundamental mistake, so I will appreciate if some one can point me to a specific knowledge base. Also, it is messing with my understanding of global variables. If I define a variable to be 'global', does that mean the variable stays to be a global variable in all the files that import this variable(or the file containing the variable definition)
The best practice for this situation would be to pass
vflag
into the functions you need as a parameter and to not use global variables.When you use
from lib import *
inprocessor.py
, you are getting a snapshot of what's going on inlib.py
at that moment. Thelib.py
file is executed, and all of the functions and variables are copied and stored in the namespace ofprocessor.py
. You are not storing references to the originalvflag
fromlib.py
- you're storing an entirely new copy. So if you changevflag
inlib.py
, thenprocessor.py
will never know about it.The better practice is to always use
import lib
, and just access the variable withlib.vflag
. You don't even need to use theglobal
keyword.