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?
Best Answer
Python relative imports are no longer strongly discouraged, but using absolute_import is strongly suggested in that case.
Please see this discussion citing Guido himself:
The OP correctly links the PEP 328 that says:
Also see almost duplicate question When or why to use relative imports in Python
Of course it still stands as a matter of taste. While it's easier to move code around with relative imports, that might also unexpectedly break things; and renaming the imports is not that difficult.
To force the new behaviour from PEP 328 use:
In this case, implicit relative import will no longer be possible (eg.
import localfile
will not work anymore, onlyfrom . import localfile
). For clean and future proof behaviour, using absolute_import is advisable.An important caveat is that because of PEP 338 and PEP 366, relative imports require the python file to be imported as a module - you cannot execute a file.py that has a relative import or you'll get a
ValueError: Attempted relative import in non-package
.This limitation should be taken into account when evaluating the best approach. Guido is against running scripts from a module in any case:
Exhaustive discussions on the matter can be found on SO; re. Python 3 this is quite comprehensive: