python中的绝对导入是什么? [英] What is absolute import in python?

查看:24
本文介绍了python中的绝对导入是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手.我正在开发一个小项目.我需要从病房开始就遵循编码标准.如何正确使用import 语句.现在我正在研究 Python 2.7.如果我移动到 3.x 是否与绝对导入有任何冲突?绝对进口和相对进口有什么区别?

I am new to Python. I am developing a small project. I need to follow coding standards from starting on wards. How to use import statements in a proper way. Now I am working on Python 2.7. If I move to 3.x are there any conflicts with absolute imports? And what is the difference between absolute and relative imports?

推荐答案

这里绘制的 absoluterelative 的区别和我们讲的很相似绝对和相对文件路径,甚至 URL.

The distinction between absolute and relative that's being drawn here is very similar to the way we talk about absolute and relative file paths or even URLs.

一个绝对的 {import, path, URL} 告诉你确切如何得到你想要的东西,通常是通过指定每个部分:

An absolute {import, path, URL} tells you exactly how to get the thing you are after, usually by specifying every part:

import os, sys
from datetime import datetime
from my_package.module import some_function

相对{imports, paths, URLs}正如他们所说的那样:它们相对于他们的当前位置.也就是说,如果目录结构发生变化或文件移动,这些可能会中断(因为它们不再意味着相同的东西).

Relative {imports, paths, URLs} are exactly what they say they are: they're relative to their current location. That is, if the directory structure changes or the file moves, these may break (because they no longer mean the same thing).

from .module_in_same_dir import some_function
from ..module_in_parent_dir import other_function

因此,对于将要共享的代码,绝对导入是首选.

Hence, absolute imports are preferred for code that will be shared.

我在评论中被要求提供一个示例,说明 from __future__ import absolute_import 如何与此相关,以及如何使用它.在试图表述这个例子时,我意识到我也无法完全解释它的行为,所以我提出了一个新问题.这个答案给出了一个代码示例,显示了 from __future__ import absolute_import 的正确工作实现,其中实际上解决了歧义.

I was asked in comments to provide an example of how from __future__ import absolute_import ties into this, and how it is meant to be used. In trying to formulate this example, I realized I couldn't quite explain its behavior either, so I asked a new question. This answer gives a code sample showing a correctly working implementation of from __future__ import absolute_import, where it actually resolves an ambiguity.

接受的答案更详细地说明了为什么会这样,包括对令人困惑的措辞的讨论Python 2.5 更新日志.本质上,该指令的范围(以及 Python 中绝对导入和相对导入之间的扩展)非常非常狭窄.如果您发现自己需要这些区别才能使您的代码正常工作,那么您最好尽可能重命名您的本地模块.

The accepted answer goes into more detail about why this works the way it does, including a discussion of the confusing wording of the Python 2.5 changelog. Essentially, the scope of this directive (and by extension the distinction between absolute and relative imports in Python) is very, very narrow. If you find yourself needing these distinctions to make your code work, you're probably better off renaming your local module if at all possible.

这篇关于python中的绝对导入是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆