When to use absolute imports

I am changing a bunch of old Python code that sometimes runs in name collisions between packages. I have a question about when to use absolute import and whether it will be correct to import modules of only one level by name.

/package/ /package/__init__.py /package/subA /package/subA/__init__.py /package/subA/moduleA.py /package/subA/moduleB.py /package/subB /package/subB/__init__.py /package/subB/moduleA.py /package/subB/moduleB.py 

Should each import statement in a package look like this:

 import package.subX.moduleX 

or

 from package.subX import moduleX 

How about in the __init__.py subpackage files. It would be wrong to just put

 import moduleA import moduleB 

Or, in /package/subA/moduleA.py, it would be wrong to just put:

 import moduleB 
+17
python import
Apr 27 '11 at 22:35
source share
1 answer

Relative imports turned out to be a very bad idea, although for a long time they were the default. You can find quite a few questions on this site where someone just named their file after the built-in module and broke their application with strange error messages.

This is why it is always useful to do absolute imports, referencing your project everywhere, including packages.

In short, use this style:

 import myproject.mypackage from myproject.mypackage.myfile import MyClass 

Quote from PEP8 :

Relative imports for in-package imports are not recommended. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its explicit relative import style is actively discouraged; absolute imports are more portable and usually more readable.

+22
Apr 27 2018-11-21T00:
source share



All Articles