在Python中导入深度嵌套的模块 [英] Importing deeply nested modules in Python
问题描述
考虑以下Python 3.6中的情况:
Consider the following case in Python 3.6:
basepackage
|---__init__.py
|---package
|---__init__.py
|---subpackage
|---__init__.py
|---module.py
重要细节:在basepackage.package.__init__.py
内有:
from basepackage.package.subpackage.module import AClass as AliasedClass
现在,让我们在要使用的basepackage.package.subpackage.module.py
中说:
Now, let's say inside basepackage.package.subpackage.module.py
we want to use:
import basepackage.package.subpackage.module as aliased_module
[1]
import basepackage.package.subpackage.module as aliased_module
[1]
结果是:
AttributeError: module 'basepackage' has no attribute 'package'
具有堆栈跟踪,列出了以下罪魁祸首语句(按以下顺序):
with a stack trace listing following culprit statements (in the below order):
from basepackage.package.subpackage.module import AClass as AliasedClass
import basepackage.package.subpackage.module as aliased_module
但是如果要使用[1]
代替:
But if instead of [1]
one'd like to use:
from basepackage.package.subpackage import module as aliased_module
[2]
from basepackage.package.subpackage import module as aliased_module
[2]
然后一切正常.
[1]
与[2]
有何不同,以致前者导致错误而后者没有错误?
How is [1]
so much different than [2]
that the former results in an error and the latter not?
推荐答案
要使第一个选项(import basepackage.package.subpackage.module as aliased_module
)起作用,必须满足以下条件:
For the first option (import basepackage.package.subpackage.module as aliased_module
) to work, these conditions have to be met:
-
basepackage/__init__.py
必须包含类似于from . import package
的行(名称package
必须在此basepackage/__init__.py
文件中定义) -
basepackage/package/__init__.py
必须包含类似于from . import subpackage
的行
-
basepackage/package/subpackage/__init__.py
必须包含类似于from . import module
的行
basepackage/__init__.py
has to contain a line similar tofrom . import package
(the namepackage
has to be defined inside thisbasepackage/__init__.py
file)basepackage/package/__init__.py
has to contain a line similar tofrom . import subpackage
basepackage/package/subpackage/__init__.py
has to contain a line similar tofrom . import module
注意:__init__.py
文件中的import语句也可以是绝对的,而不是相对路径.
Note: the import statements inside the __init__.py
files can also be absolute instead of relative paths.
对于第二个选项(from basepackage.package.subpackage import module as aliased_module
),只要每个__init__.py
文件都存在,则每个级别上都有空的__init__.py
文件就足够了.
For the second option (from basepackage.package.subpackage import module as aliased_module
), it is enough if there are empty __init__.py
files at each level, as long as these __init__.py
files exist.
这篇关于在Python中导入深度嵌套的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!