[解决方案]SystemError: Parent module '' not loaded, cannot perform relative import的解决方案

缺陷:__mian__不能使用相对导入

PEP 328 Relative Imports and __name__ 中说明:

Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

即:相对导入在 package 分层中,使用模块的__name__ 属性得到模块的位置。但是如果模块的名字没有包含任何 package 信息(例如,__main__模块),不管是否该模块实际位于文件系统,相对导入会被当作顶层模块导入(a top level module)。

修复

根据 6.4.2. Intra-package References 的建议:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

__mian__ 使用 绝对导入 方式,而其他模块仍使用 相对导入

if __name__ == '__main__':
   sys.path.append(os.path.dirname(sys.path[0]))

后话

导入的方式

参考 stackoverflow vaultah 的回答,比较详细,这里不再赘述。

为什么选择相对导入的优势

PEP 328 Rationale for Relative Imports 中说明:

Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages.In addition, a module inside a package can't easily import itself without relative imports.

即:相对导入可以对大型的 python packages 重构时,不用重新编辑 sub-packages;另外,相对导入可以比较轻松地导入自身。

原文地址:https://www.cnblogs.com/cposture/p/5492351.html