简体   繁体   中英

From module import global variable

Considering this project structure:

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

And these imports and declarations:

# __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'

Is the message I've been receiving and I suppose there's something related with the cyclic import structure, but I tried some other organizations without success. So I was wonder how to solve this situation.

  1. What is the Pythonic file structure for related modules like this?
  2. How should I store a global variable to be able to import it along with the whole project?

Yes, the problem is, as @juanpa.arrivillaga said, in you circular/cyclic imports. This answer explains how your problem occurs in detail. This question and answer has a similar problem as you and has a quick fix.

Your file structure is not the problem. However, you could use the 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 .

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