python - 导入语句python3的变化

我不明白 pep-0404 的以下内容

In Python 3, implicit relative imports within packages are no longer available - only absolute imports and explicit relative imports are supported. In addition, star imports (e.g. from x import *) are only permitted in module level code.

什么是相对导入? 在 python2 中允许在哪些其他地方进行星形导入? 请举例说明。

最佳答案

每当您导入相对于当前脚本/包的包时,就会发生相对导入。

以下面的树为例:

mypkg
├── base.py
└── derived.py

现在,您的 derived.py 需要来自 base.py 的内容。在 Python 2 中,您可以这样做(在 derived.py 中):

from base import BaseThing

Python 3 不再支持这一点,因为它不明确你想要“相对”还是“绝对”base。换句话说,如果系统中安装了一个名为 base 的 Python 包,那么你会得到错误的包。

相反,它要求您使用显式导入,它在类似路径的基础上显式指定模块的位置。您的 derived.py 看起来像:

from .base import BaseThing

前导 . 表示“从模块目录导入 base”;换句话说,.base 映射到 ./base.py.

类似地,有 .. 前缀,它会像 ../ 一样在目录层次结构中上升(..mod 映射到 ../mod.py),然后是 ... 向上两级 (../../mod.py) 等等开。

但是请注意,上面列出的相对路径是相对于当前模块 (derived.py) 所在的目录,不是当前工作目录。


@BrenBarn 已经解释了明星导入案例。为了完整起见,我不得不说同样的话;)。

例如,您需要使用一些 math 函数,但您只能在单个函数中使用它们。在 Python 2 中,你被允许是半懒惰的:

def sin_degrees(x):
    from math import *
    return sin(degrees(x))

请注意,它已经在 Python 2 中触发了警告:

a.py:1: SyntaxWarning: import * only allowed at module level
  def sin_degrees(x):

在现代 Python 2 代码中你应该这样做,而在 Python 3 中你必须这样做:

def sin_degrees(x):
    from math import sin, degrees
    return sin(degrees(x))

或:

from math import *

def sin_degrees(x):
    return sin(degrees(x))

https://stackoverflow.com/questions/12172791/

相关文章:

linux - 并排显示两个文件

c - 如何设置 cron 作业以每小时运行一次可执行文件?

linux - 安装 Jenkins 后无法 su 到用户 jenkins

Linux - 替换文件名中的空格

python - 定义Python源代码编码的正确方法

python - 是否可以将已编译的 .pyc 文件反编译为 .py 文件?

linux - 如何从文本文件中删除换行符?

python - 在类方法上使用 property()

linux - 错误 : Can't open display: (null) when using

python - 在pytest中,conftest.py文件有什么用?