导入语句python3中的更改

2024-04-24 06:42:30 发布

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

我不明白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中,还有哪些地方允许引入恒星? 请举例说明。


Tags: andnoinonlypackagesareimportspep
3条回答

有关相对导入,请参见the documentation。相对导入是指相对于模块的位置从模块导入,而不是绝对从sys.path导入。

对于import *,Python 2允许在函数中进行星型导入,例如:

>>> def f():
...     from math import *
...     print sqrt

Python 2中对此发出警告(至少是最新版本)。在Python 3中,它不再被允许,您只能在模块的顶层(而不是在函数或类内部)执行星型导入。

要同时支持Python2和Python3,请使用如下所示的显式相对导入。它们是相对于当前模块的。他们得到了支持。

from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle

相对导入在导入相对于当前脚本/包的包时发生。

以下面的树为例:

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

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

from base import BaseThing

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

相反,它要求您使用显式导入(explicit imports)来显式地指定模块在相同路径上的位置。你的derived.py看起来像:

from .base import BaseThing

前面的.表示“importbasefrom module directory”;换句话说,.base映射到./base.py

类似地,还有..前缀,它在目录层次结构中像../(将..mod映射到../mod.py),然后...在两个级别上(../../mod.py)等等。

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


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

例如,您需要使用几个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):

在现代的Python2代码中,您应该这样做,而在Python3中,您必须这样做:

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

或:

from math import *

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

相关问题 更多 >