简体   繁体   中英

Accessing a Python global variable across files

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)

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.

这种情况的最佳实践是将vflag传递vflag您需要的函数作为参数并且不使用全局变量。

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