什么是兄弟进口?

What are sibling imports?

2to3 - Automated Python 2 to 3 code translation - Fixers - import 注意:

Detects sibling imports and converts them to relative imports.

是指导入同一父目录下的模块

在此目录结构中:

parent
    module1
        __init__.py
        module1.py
    module2
        __init__.py
        module2.py

例如,兄弟导入指的是从 module2.py.

导入 module1

来自source code

"""Fixer for import statements.
If spam is being imported from the local directory, this import:
    from spam import eggs
Becomes:
    from .spam import eggs
And this import:
    import spam
Becomes:
    from . import spam
"""

所以 sibling 将代表 "on the same level".

"""Fixer for import statements.
If spam is being imported from the local directory, this import:
    from spam import eggs
Becomes:
    from .spam import eggs
And this import:
    import spam
Becomes:
    from . import spam
"""

导入本地模块时会发生变化,在本地有一个__init__.py

-- local path
  -- a.py
  -- b.py
  -- __init__.py


RefactoringTool: Refactored a.py
--- a.py    (original)
+++ a.py    (refactored)
@@ -1,2 +1,2 @@
-import b
-print 'xxx'
+from . import b
+print('xxx')
RefactoringTool: Files that need to be modified:
RefactoringTool: a.py

详情见:probably_a_local_import

兄弟导入 不是 技术终点。在你的问题的上下文中,它意味着:

  • 相同目录导入一个文件(所以导入 文件和 imported 文件是 siblings 相对于文件系统),或

  • 这样的文件中导入一个模块(多个模块)


注:

问题源于 Python 2 和 Python 3 导入系统之间的微小差异,但首先让我们将文件系统路径与 [=11= 中使用的 packages/modules 路径进行比较] 或 from ... import 语句:

+---+--------------------------+-------------------------+
|   |    In the File system    |   In the Python import  |
+---+--------------------------+-------------------------+
| 1 | /doc/excel               |  doc.excel              | <--- absolute
| 2 |   excel (we are in /doc) |   excel (we are in doc) | <--- ???
| 3 | ./excel (we are in /doc) |  .excel (we are in doc) | <--- relative
+---+--------------------------+-------------------------+

实质性区别在于:

在文件系统中,我们总是将绝对路径识别为以/(或类似的东西)开头的路径,所以前面table中的情况2和3具有相同的含义 - 都是相对路径。

但在Python导入系统中,情况2表示:在当前模块中搜索excel(即在doc中) ,但如果没有找到,则认为是顶层模块。这可能会产生问题。

2to3.py 分析此类模棱两可的(案例 2)进口,试图确定其中哪些是 兄弟姐妹 (在此答案顶部提到的含义) ,并将它们转换为 明确相关的(即转换为案例 3)

(情况 3 始终明确 - 前导 . 表示 相对 路径,即模块 doc.excel).