import语句中的更改python3

我不明白以下来自PEP-0404的内容

在Python3中,包内的隐式相对导入不再 可用-只有绝对导入和显式相对导入 支持。此外,星号导入(例如,从X导入*)仅 在模块级代码中允许。

什么是相对进口? 在Python2中还有哪些地方允许星号导入? 请举例说明。

145159 次浏览

有关相对导入的信息,请参阅文档。相对导入是指从相对于模块位置的模块中导入,而不是绝对从sys.path中导入。

对于import *,Python2允许在函数中导入星号,例如:

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

在Python2(至少是最近的版本)中对此发出了警告。在Python3中,它不再被允许,并且您只能在模块的顶层(而不是在函数或类内部)进行星型导入。

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

以下面的树为例:

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

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

from base import BaseThing

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

相反,它要求您使用显式导入,它在类似路径的基础上显式地指定模块的位置。derived.py将如下所示:

from .base import BaseThing

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

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

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


_,ABC_0已经解释了Star导入案例。为了完整起见,我不得不说同样的话。

例如,您需要使用几个math函数,但您只在单个函数中使用它们。在Python2中,你可以是半懒惰的:

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

要同时支持Python2和Python3,请使用显式相对导入,如下所示。它们与当前模块相关。它们在从2.5开始中得到支持。

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

在MichałGórny的回答中增加了另一个案例:

请注意,相对导入基于当前模块的名称。由于主模块的名称始终为“__main__ ”,因此打算用作Python应用程序主模块的模块必须始终使用绝对导入。