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

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

问题描述

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

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

我问这个问题是因为我想创建一个不确定性的包,可以用作

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.

我不想重命名不确定因素。因为这个模块正好用于替换数学模块中的函数(具有处理数值不确定性的等价物)。

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 <的绝对/相对导入/ a>, 2.5及以上

在Python 2.5中,您可以使用from __future__ import absolute_import指令将导入行为切换为绝对导入。这种绝对导入行为将成为未来版本(可能是Python 2.7)的默认行为。一旦绝对导入是默认导入,导入数学将始终找到标准库的版本。建议用户应尽可能多地开始使用绝对导入,因此最好从代码中的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 ... import表单时,通过向模块名称添加前导句点仍然可以进行相对导入:

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天全站免登陆