在python中,为什么导入嵌套模块会出现ModuleNotFoundError?

时间:2021-07-13 19:34:11

标签: python python-3.x python-import

我有以下结构:

/
    script.py            # from package.module import Something
    package/             # Parent. Nested pkg/* directly accessible
        __init__.py      # Imports module from nested pkg.
        package/         # Nesting should be transparent
            __init__.py
            module.py    # Defines class Something

文件内容为:

# script.py:
from package.module import Something

# /package/__init__.py
from .package import module
print('Parent imported module:\n', module)
print('Parent imported class:\n', module.Something)

# /package/package/__init__.py
from . import module
print('Local imported module:\n', module)
print('Local imported class:\n', module.Something)

# /package/package/module.py
class Something:
    pass

运行 script.py 给出以下输出:

Local imported module:
 <module 'package.package.module' from '\\package\\package\\module.py'>
Local imported class:
 <class 'package.package.module.Something'>
Parent imported module:
 <module 'package.package.module' from '\\package\\package\\module.py'>
Parent imported class:
 <class 'package.package.module.Something'>
Traceback (most recent call last):
  File ".\script.py", line 1, in <module>
    from package.module import Something
ModuleNotFoundError: No module named 'package.module'

因此,从打印语句中可以看出,父文件和嵌套 __init__.py 文件能够导入嵌套模块。然而,即使在导入了嵌套的模块和类之后,脚本最终还是会抛出异常。

但是,如果我将 script.py 的内容更改为:

from package import module
print(module.Something)   # works!

from module import Something  # ModuleNotFoundError!
print(Something)

为什么?怎么修?

0 个答案:

没有答案