不带sys或os的相对导入校正

2024-05-29 08:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了几乎所有的解决方案,以修复相对进口,他们似乎没有一个工作。以下是我目前的结构:

structures
\ containers
  \ queue.py
\ trees
  \ binaryTree.py

我想将队列导入到我的二叉树文件中,但是我遇到了相对导入问题。我试过__init__.py,但这似乎并不能解决相对的导入问题。有解决办法吗?(我使用的是Python 3.3.x)

编辑:

这是我的进口报关单

from .containers.queue import Queue

错误是:

Traceback (most recent call last):
  File "binaryTree.py", line 1, in <module>
    from .containers.queue import Queue
SystemError: Parent module '' not loaded, cannot perform relative import

Tags: 文件frompyimport队列queue解决方案结构
2条回答

将包模块作为脚本运行是一种“有趣”的体验。默认情况下,脚本不是包的一部分,对相对导入一无所知。假设脚本在已安装的环境中运行,并且使用绝对导入。distutils例如,安装软件包时将它们放在不同的目录中。你知道吗

如果您的脚本隐藏在包发行版中,它可以通过将其包目录的父目录添加到sys.path并执行绝对导入来欺骗系统。这是危险的,因为现在所有与包dir对等的目录都是潜在的python模块。你知道吗

pep 366定义在脚本中执行相对导入的方法:

When the main module is specified by its filename, then the package attribute will be set to None . To allow relative imports when the module is executed directly, boilerplate similar to the following would be needed before the first relative import statement:

if name == "main" and package is None: package = "expected.package.name"

Note that this boilerplate is sufficient only if the top level package is already accessible via sys.path . Additional code that manipulates sys.path would be needed in order for direct execution to work without the top level package already being importable.

但在我看来还是很尴尬。希望有人有一个更干净的方法来做这件事,但这是我认为你需要的:

if __name__ == "__main__" and __package__ is None:
    # name package for relative imports
    __package__ = "structures.trees"
    # add package dir to python path
    import os
    import sys
    pkg_parent = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
    sys.path.insert(0, pkg_parent)
    # ...and import
    import structures.trees

from ..containers.queue import Queue

但你还是有问题。如果包导入binaryTree,python会认为它是与脚本不同的模块,因此所有内容(包括副作用)都会被复制。你知道吗

 from ..containers.queue import Queue

相关问题 更多 >

    热门问题