从模块导入全局变量

From module import global variable

考虑这个项目结构:

project
  ...
   |-- view
        |-- __init__.py
        |-- app_view.py
        |-- component.py

以及这些导入和声明:

# __init__.py
from view.app_view import AppView
global APP_VIEW
APP_VIEW = AppView()


# app_view.py
from view.component import Component
class AppView:
    def __init__(self):
        self.component = Component()   


# component.py
from view import APP_VIEW
class Component:
   ...

ImportError: cannot import name 'APP_VIEW'

是我一直收到的消息,我想这与循环导入结构有关,但我尝试了一些其他组织但没有成功。所以我想知道如何解决这种情况。

  1. 像这样的相关模块的 Pythonic 文件结构是什么?
  2. 我应该如何存储全局变量以便能够将其与整个项目一起导入?

是的,问题是,正如@juanpa.arrivillaga所说,在你circular/cyclic进口。 This answer 详细解释了您的问题是如何发生的。 This question and answer 遇到了和你类似的问题,并且有一个快速修复。

你的文件结构不是问题。但是,您可以使用 singleton pattern, instead of a global variable, in order to archive what you want to do. Here is a comparison in python projects of these two ways.