本文介绍了当存在同名的本地模块时,如何在 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.

在使用 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 中访问标准库模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:57