简体   繁体   中英

Nested module and package imports in Python

We have a VERY large python project (200+ files)

and up till now I've been handling it dependencies very well there are a few spots where some new part of the project used and existing part from another module and it's been simple enough to make sure everything imports in the right order.

but now I'm getting into trouble when a module in a sub-package requires a module form another sub-package

to illustrate take this simplified version

the file system

Core
|__init__.py
|Database
-|__init__.py
-|Dialogs
--|__init__.py
--|SomeDialog.py
-|Controls
--|__init__.py
--|SomeControl.py
|Frame.py

now if in SomeControl.py I import SomeDialog.py via this statement from Core.Dialogs.SomeDialog import SomeDialog where SomeDialog is a class in the file Somedialog

When I go to import Core in the main application I get an error that "Core" has no module "Database"

how can I fix this?

This case names "circular imports". You can import your modules in functions and methods just you need to use them.

# SomeDialog.py
class Dialog(object):
    def draw(self):
        from ..Controls.SomeControl import control
        control()

# SomeControl.py
def control():
    from ..Dialogs.SomeDialog import all_dialogs
    do_something(all_dialogs)

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