Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a standard-library module in Python when there is a local module with the same name?

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 *

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: this question pertains to the module I wrote for performing calculations with uncertainties while taking into account correlations between variables.

like image 774
Eric O Lebigot Avatar asked Dec 14 '09 10:12

Eric O Lebigot


People also ask

Do Python modules need to be in the same folder?

Answer. No, files can be imported from different directories.

How do I access a Python module?

In Python, modules are accessed by using the import statement. When you do this, you execute the code of the module, keeping the scopes of the definitions so that your current file(s) can make use of these.

How do I find the default modules in Python?

To see all the installed modules you can use the following command in python interpreter. help("modules") . It will show all the installed modules. If you are looking for inbuilt functions like print use the command help(__builtins__) in python shell.

Is Python library and module same?

A module is a collection of code or functions that uses the . py extension. A Python library is a set of related modules or packages bundled together. It is used by the programmers as well as the developers.


1 Answers

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

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.

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
like image 60
mbarkhau Avatar answered Oct 13 '22 00:10

mbarkhau