Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python absolute import in module fails

I have a project which looks like this:

my_project/
          __init__.py -- empty
          run.py
          datacheck/
                  __init__.py -- empty
                  datacheck.py -- containing class DataCheck(object)
                  config.py -- containing BusinessConfig(object)
                  business.py -- containing class BusinessCheck(DataCheck)

My PYTHONPATH is configured to have /my_project in it.

In run.py, I have the following code:

from datacheck.business import BusinessCheck
business = BusinessCheck()
business.check_data()

In business.py, I have the following imports that fail:

from datacheck.config import BusinessConfig
from datacheck.datacheck import DataCheck

A relative import like from .config import BusinessConfig works - however I've read in numerous threads that an absolute import is preferred.

To do a simple test, I also created the following:

myproject/
          __init__.py -- empty
          run_test.py
          test/
              __init__.py -- empty
              test1.py -- containing class Test1(object)
              test2.py -- containing class Test2(Test1)

run_test.py imports and runs the Test2 class, this didn't fail.

It left me a bit flabbergasted, I don't understand why my absolute imports in datacheck are not working - can anyone explain?

like image 971
Sjaak Trekhaak Avatar asked Nov 16 '11 10:11

Sjaak Trekhaak


2 Answers

You should prefer absolute imports if your module can be used as __main__, as explained in the documentation. If not, relative imports are fine.

These imports fail, because your package datacheck contains a module datacheck (same name). When looking up the name, Python implicitly looks inside the package first. There, it finds the module datacheck. This module, however, does not contain anything with the name config, so the import fails.

If you want to use absolute imports, move all the stuff from the module datacheck into the __init__.py of the package, or rename it.

like image 109
Björn Pollex Avatar answered Sep 20 '22 17:09

Björn Pollex


I know this is many years later, but for the sake of others searching here, I was able to resolve a similar problem with this bit of code:

from __future__ import absolute_import

After that, absolute imports worked fine in Python 2.6 and 2.7.

like image 26
Steve Avatar answered Sep 22 '22 17:09

Steve