导入语句python3的变化

我不明白以下从pep-0404

在Python 3中,包内的隐式相对导入不再可用 – 仅支持绝对导入和显式相对导入。 此外,明星import(例如从x导入*)只允许在模块级代码。

什么是相对导入? 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 

领先. 说'从模块目录importbase '; 换句话说, .base映射到./base.py

类似的,有..前缀上升的目录层次像../ (与..mod映射到../mod.py ),然后...这两个层次( ../../mod.py )等等。

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


@BrenBarn已经解释了明星import案例。 为了完整性,我将不得不说同样的;)。

例如,您需要使用一些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)) 

相对import请参阅文档 。 相对导入是从模块相对于该模块的位置导入的,而不是绝对从sys.path导入的。

至于import * ,Python 2允许在函数内import *星标,例如:

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

在Python 2中发布了一个警告(至less是最近的版本)。 在Python 3中,不再允许,只能在模块的顶层(不在函数或类中)进行星形导入。

要同时支持Python 2和Python 3,请使用如下所示的显式相对导入。 他们是相对于当前模块。 他们从2.5开始获得支持。

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