Accessing a Python global variable across files

2019-02-19 17:28发布

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)

2条回答
对你真心纯属浪费
2楼-- · 2019-02-19 17:40

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.

查看更多
我只想做你的唯一
3楼-- · 2019-02-19 17:41

When you use from lib import * in processor.py, you are getting a snapshot of what's going on in lib.py at that moment. The lib.py file is executed, and all of the functions and variables are copied and stored in the namespace of processor.py. You are not storing references to the original vflag from lib.py - you're storing an entirely new copy. So if you change vflag in lib.py, then processor.py will never know about it.

The better practice is to always use import lib, and just access the variable with lib.vflag. You don't even need to use the global keyword.

查看更多
登录 后发表回答