简体   繁体   中英

Python design - cross imports

I'm stuck with imports and don't know how to address the issue.

I have 3 modules:

  1. test_project.py
  2. modules/__init__.py
  3. r.py
  4. module.py
  5. module_configuration.py

The list of dependencies:

test_project.py IMPORTS modules/__init__.py
modules/__init__.py IMPORTS r.py 
r.py IMPORTS > module_configuration.py 
module_configuration.py IMPORTS > modules/__init__.py

So as you can see, we have a circular import here.

  • modules/__init__.py keeps dict of class definitions (class like R).
  • R class makes instance of ModuleConfiguration in its constructor
  • ModuleConfiguration needs dict of classes from modules/__init__.py .

Error message I get:

ERROR: controller.test_project (unittest.loader.ModuleImportFailure)
----------------------------------------------------------------------
ImportError: Failed to import test module: controller.test_project
Traceback (most recent call last):
File "/usr/lib/python2.7/unittest/loader.py", line 252, in _find_tests
module = self._get_module_from_name(name)
File "/usr/lib/python2.7/unittest/loader.py", line 230, in  
_get_module_from_name__import__(name)
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/controller/test_project.py",    
line 9, in <module>
from c.core.modules import MODULES
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/modules/__init__.py", line 5, in <module>
from R import R
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/modules/R.py", line  6, in <module>
from c.core.module import Module
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/module.py", line 13, in <module>
from c.core.module_configuration import ModuleConfiguration
File "/media/103AEB9B3AEB7C5A/Projekty/c/svn/tests/../c/core/module_configuration.py", line 7, in <module>
from c.core.modules import MODULES

ImportError: cannot import name MODULES

Any ideas on how to solve it?

Instead of making the instances at module load time, implement functions returning the relevant results and keep these functions in their respective modules. Then once the modules are loaded everything is available to all. There's nothing wrong with importing moduleA from moduleB and moduleB from moduleA. Do you need module global objects that must be created at module load time? This is usually not needed. Instead try to construct whatever module globals are required at first use once all modules are in place.

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