【问题标题】:How to manage relative imports in python?如何在 python 中管理相对导入?
【发布时间】:2017-06-17 12:28:23
【问题描述】:

我有一个结构如下的代码:

  mainDir/
         /foo/ __init__.py
         /foo/foo.py  (i am importing bar here)
         /__init__.py
         /bar.py

现在, foo.py 有一个类似的导入

from ..bar import *

在 mainDir 中我正在尝试运行:python -m foo.foo。但我得到:

ValueError: 尝试在 foo.py 中的顶级包之外进行相对导入以尝试导入 bar

我不是在寻找sys.path 解决方案,而是在创建模块?有什么建议吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    使用绝对导入:

    from bar import *  # though you shouldn't be using import * anyway
    

    相对导入必须保留在一个包中。您不能完全跳出包层次结构并通过相对导入导入顶级模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多