简体   繁体   English

在已安装的Python包中导入

[英]Imports within an installed Python package

Consider the following directory structure for an installed Python package: 对于已安装的Python软件包,请考虑以下目录结构:

project/
    project/
        __init__.py
        file1.py
        file2.py
        module/
            __init__.py
            file3.py
    setup.py

In order to access a function in file2.py from file1.py , one could do 为了从file1.py访问file2.py的函数,可以执行以下操作

from file2 import fun

Or 要么

from project.file2 import fun

Analogously, if from file1.py I wanted to access a function in file3.py , I could do from project.module.file3 import function or from .module.file3 import function . 类似地,如果我想从file1.py访问file3.py的函数, file3.py可以from project.module.file3 import functionfrom .module.file3 import function

These two options appear to be equivalent. 这两个选项似乎是等效的。 Is there a preferred method, or a relevant difference between the two that I am missing? 是否有首选的方法,或者我所缺少的两者之间存在相关差异?

Although this is mostly a matter of personal preference, PEP8 recommends using absolute imports: 尽管这主要是个人喜好问题,但PEP8建议使用绝对导入:

from project.module.file3 import function 

rather than relative imports: 而不是相对进口:

from .module.file3 import function

Absolute imports are more readable and better behaved (better error messages upon failure). 绝对导入更具可读性和更好的行为(失败时出现更好的错误消息)。 BUT, when using absolute imports becomes unnecessarily verbose (use your judgement), using relative imports is an acceptable alternative. 但是,当使用绝对导入变得不必要的冗长时(使用您的判断),可以使用相对导入。 See this PEP8 documentation on imports. 请参阅有关进口的PEP8文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM