当存在同名的本地模块时,如何在 Python 中访问标准库模块? [英] How to access a standard-library module in Python when there is a local module with the same name?

查看:30
本文介绍了当存在同名的本地模块时,如何在 Python 中访问标准库模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当文件 prog.py 与具有相同名称的本地模块 (math.py) 放在同一目录中时,如何访问标准库模块(例如 math)?

How can a standard-library module (say math) be accessed when a file prog.py is placed in the same directory as a local module with the same name (math.py)?

我问这个问题是因为我想创建一个可以用作uncertainties的包

I'm asking this question because I would like to create a package uncertainties that one can use as

import uncertainties
from uncertainties.math import *

因此,不确定性目录中有一个本地数学模块.问题是我想从不确定性/__init__.py 访问标准库数学模块.

Thus, there is a local math module inside the uncertainties directory. The problem is that I want to access the standard library math module from uncertainties/__init__.py.

我不想重命名不确定性.math,因为这个模块正是为了替换数学模块中的函数(使用处理数值不确定性的等价物).

I prefer not to rename uncertainties.math because this module is precisely intended to replace functions from the math module (with equivalents that handle numerical uncertainties).

PS:这个问题与我为执行不确定性计算而编写的模块有关.考虑变量之间的相关性.

PS: this question pertains to the module I wrote for performing calculations with uncertainties while taking into account correlations between variables.

推荐答案

您正在寻找来自 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

这篇关于当存在同名的本地模块时,如何在 Python 中访问标准库模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆