Tuesday, 24 May 2016

package - Absolute vs. explicit relative import of Python module



I'm wondering about the preferred way to import packages in a Python application. I have a package structure like this:



project.app1.models
project.app1.views
project.app2.models



project.app1.views imports project.app1.models and project.app2.models. There are two ways to do this that come to mind.



With absolute imports:



import A.A
import A.B.B


or with explicit relative imports, as introduced in Python 2.5 with PEP 328:




# explicit relative
from .. import A
from . import B


What is the most pythonic way to do this?


Answer



Absolute imports. From PEP 8:





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




Explicit relative imports are a nice language feature (I guess), but they're not nearly as explicit as absolute imports. The more readable form is:




import A.A
import A.B.B


especially if you import several different namespaces. If you look at some well written projects/tutorials that include imports from within packages, they usually follow this style.



The few extra keystrokes you take to be more explicit will save others (and perhaps you) plenty of time in the future when they're trying to figure out your namespace (especially if you migrate to 3.x, in which some of the package names have changed).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...