简体   繁体   English

Python中的嵌套模块和包导入

[英]Nested module and package imports in Python

We have a VERY large python project (200+ files) 我们有一个非常大型的python项目(超过200个文件)

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 现在如果在SomeControl.py我进口SomeDialog.py通过这一说法from Core.Dialogs.SomeDialog import SomeDialog其中SomeDialog是文件中的一类Somedialog

When I go to import Core in the main application I get an error that "Core" has no module "Database" 当我在主应用程序中import Core ,出现错误消息“ Core”没有模块“ 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM