Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a module whose name clashes with a module in my package?

Tags:

python

import

I have several python modules in a directory.

In the same directory, I have a package tests.

I would quite like to name the modules in tests the same as the modules that they contain tests for, although of course it isn't critical.

So, in tests.foo I naively write import foo. This isn't working so well - it imports tests.foo, not top-level foo.

Can I do what I want, or do I just have to call the test module test_foo?

Sorry if this is obvious or a dupe, my search-fu has failed.

like image 882
Steve Jessop Avatar asked Jan 27 '11 12:01

Steve Jessop


People also ask

How do you resolve a name conflict in Python?

The easiest and most sane way to do it is to refactor you project and change the name of the file.

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 import a module from a package?

Importing module from a package We can import modules from packages using the dot (.) operator. Now, if this module contains a function named select_difficulty() , we must use the full name to reference it. Now we can directly call this function.

Which statement is used to import a particular module from the package?

The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.


2 Answers

test_foo.py seems like an appropriate solution in this case.

If you don't rename the test modules then make the tests directory into Python package (add tests/__init__.py file) and use absolute imports:

from __future__ import absolute_import 
import foo                   # import global foo.py, the first foo.py in sys.path
import tests.foo as test_foo # import tests/foo.py
like image 154
jfs Avatar answered Oct 18 '22 23:10

jfs


Use the full package path like this:

--Package
   |-- __init__.py
   |-- foo.py
   |
   |-- tests
   |    | -- __init__.py
        | -- foo.py

in tests/foo.py do

from Package import foo

And i think this part of the documentation can interest you : http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

like image 3
mouad Avatar answered Oct 18 '22 23:10

mouad