Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I choose which module to import when they are named the same

Lets say I'm in a file called openid.py and I do :

from openid.consumer.discover import discover, DiscoveryFailure

I have the openid module on my pythonpath but the interpreter seems to be trying to use my openid.py file. How can I get the library version?

(Of course, something other than the obvious 'rename your file' answer would be nice).

like image 869
Paul Tarjan Avatar asked Aug 11 '09 08:08

Paul Tarjan


People also ask

Can two different packages have modules with same name?

This is not possible with the pip. All of the packages on PyPI have unique names. Packages often require and depend on each other, and assume the name will not change. Even if you manage to put the code on Python path, when importing a module, python searches the paths in sys.

How do I import a specific module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How do you use relative import in Python?

Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above.

Where does Python look when for modules or packages when import is called?

Python looks for modules in “sys. It looks for a file called a_module.py in the directories listed in the variable sys. path .


1 Answers

Thats the reason absolute imports have been chosen as the new default behaviour. However, they are not yet the default in 2.6 (maybe in 2.7...). You can get their behaviour now by importing them from the future:

from __future__ import absolute_import

You can find out more about this in the PEP metnioned by Nick or (easier to understand, I think) in the document "What's New in Python 2.5".

like image 142
c089 Avatar answered Sep 24 '22 21:09

c089