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?
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
datacheckcontains a moduledatacheck(same name). When looking up the name, Python implicitly looks inside the package first. There, it finds the moduledatacheck. This module, however, does not contain anything with the nameconfig, so the import fails.If you want to use absolute imports, move all the stuff from the module
datacheckinto the__init__.pyof the package, or rename it.