什么是兄弟进口?

2024-05-20 00:01:07 发布

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

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

Detects sibling imports and converts them to relative imports.


Tags: andtoimportcodetranslationimportsconvertsrelative
3条回答
"""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时,它将发生变化

^{pr2}$

详见:probably_a_local_import

兄弟进口不是终点技术。在你的问题中,这意味着:

  • 从同一目录导入文件(因此导入文件和导入的文件相对于文件系统是同级的,或

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


注意:

这个问题源于Python2和Python3导入系统之间的细微差别,但是首先让我们比较一下文件系统路径与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
+---+--------------------------+-------------------------+

实质性的区别在于:

在文件系统中,我们总是认为绝对路径是以/(或类似的)开头的路径,因此上表中的情况2和3具有相同的含义—两者都是相对的路径。在

但是在Python导入系统中,情况2意味着:在当前模块中搜索excel(即在doc)中,,但如果没有找到,则将其视为顶层模块。这会产生问题。在

2to3.py分析了这种模棱两可的(案例2)导入,试图确定其中哪些是同级的(在这个答案顶部提到的含义),并将它们转换为明确的相对关系(即,转换为案例3)。在

(情况3是总是明确的-前导.表示相对路径,即模块doc.excel)。在

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
"""

因此,兄弟将代表“在同一水平上”。在

相关问题 更多 >