且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当存在同名的本地模块时,如何在 Python 中访问标准库模块?

更新时间:2023-11-08 16:13:04

您正在寻找来自 PEP 328,可用于 2.5 及更高版本.

You are looking for Absolute/Relative imports from PEP 328, available with 2.5 and upward.

在 Python 2.5 中,您可以使用 from __future__ import absolute_import 指令将导入的行为切换为绝对导入.这种绝对导入行为将成为未来版本(可能是 Python 2.7)中的默认行为.一旦绝对导入成为默认值,import math 将始终找到标准库的版本.建议用户尽可能地开始使用绝对导入,因此***在代码中从 pkg import string 开始编写.
In Python 2.5, you can switch import‘s behaviour to absolute imports using a from __future__ import absolute_import directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, import math will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing from pkg import string in your code.

在使用 from ... 导入形式时,通过在模块名称中添加前导句点,仍然可以进行相对导入:

Relative imports are still possible by adding a leading period to the module name when using the from ... import form:

from __future__ import absolute_import
# Import uncertainties.math
from . import math as local_math
import math as sys_math