在 3 个文件之间导入的全局变量

Global variable with imports between 3 files

我来自 this thread 这很有帮助但还不够。我的情况略有不同,但最重要的是我的情况:我正在重构 1000 多行代码(在一个文件中),因此更改名称很快就会变得很痛苦。

所以我将文件分成 3 个:

我会简化这里的内容。

settings.py:

MY_VAR = "plane"

synchro.py:

from settings import *
import groups

def main():
  global MY_VAR
  MY_VAR = "boat"
  groups.update()

groups.py:

from settings import *

def update():
  print MY_VAR # will print "plane" instead of "boat"

我也尝试写 import settings 而不是 from settings import * 但在那种情况下 python 告诉我 global settings.MY_VAR 是一个错误,它无法识别 settings.MY_VAR 如果我删除 global 行。

那么 quickest/easiest 完成这项工作的方法是什么?

感谢您的帮助

你应该像下面那样做,不建议这样做 from settings import * ,它会导致命名空间污染并使以后更难调试。 我通常只在同一个文件中使用全局,尽管我尽可能减少全局使用

settings.py

MY_VAR = "plane"

synchro.py:

import settings
import groups

def main():
  # no need to declare global here, access trough settings namespace instead
  settings.MY_VAR = "boat"
  groups.update()

groups.py:

import settings

def update():
  print settings.MY_VAR # will print "plane" at first, after synchro main, MY_VAR should carry 'boat'