0

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?
artu-hnrq
  • 1,343
  • 1
  • 8
  • 30

1 Answers1

1

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.

artu-hnrq
  • 1,343
  • 1
  • 8
  • 30
LinFelix
  • 1,026
  • 1
  • 13
  • 23