109

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?

Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75

3 Answers3

147

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:

"Isn't this mostly historical? Until the new relative-import syntax was implemented there were various problems with relative imports. The short-term solution was to recommend not using them. The long-term solution was to implement an unambiguous syntax. Now it is time to withdraw the anti-recommendation. Of course, without going overboard -- I still find them an acquired taste; but they have their place."

The OP correctly links the PEP 328 that says:

Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports.

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:

from __future__ import absolute_import

In this case, implicit relative import will no longer be possible (eg. import localfile will not work anymore, only from . 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:

I'm -1 on this and on any other proposed twiddlings of the __main__ machinery. The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern. To make me change my mind you'd have to convince me that it isn't.

Exhaustive discussions on the matter can be found on SO; re. Python 3 this is quite comprehensive:

Community
  • 1
  • 1
Stefano
  • 18,083
  • 13
  • 64
  • 79
  • 13
    Guido wrote that in 2010 and it's still in the PEP? How can we trust PEPs if they are so outdated? – Jabba Jan 03 '14 at 11:45
  • 5
    PEP are like US amendments in the sense that you can amend things. There are lot of rejected PEPS too. PEPs are proposals. They can be accepted, rejected or become obsolete which often means new PEP. PEP 8 is a style guide so it can be modified in place. – CppLearner May 31 '14 at 02:40
  • 3
    I am confused about the "a module inside a package can't easily import itself... " part. I had never heard about modules importing themselves before. – matiascelasco Dec 03 '14 at 00:06
  • 2
    One possible example @matiascelasco : if you have foo/bar.py and foo/baz.py but also baz.py somewhere else. If you want to import foo.baz from bar you might want to be sure of what you are importing, eg. `import .baz` - this is just one simplistic of many similar situations described in the PEP though. – Stefano Dec 03 '14 at 16:41
  • Your answer doesn't clearly distinguish the change in allowing them. Implicit relative imports should never be used, but explicit relative imports are ok to use. Implicit relative has been removed from Python3. – ninMonkey Sep 13 '15 at 15:04
  • @ninMonkey agreed on Py3 should be part of the answer. I assumed the question was for Py2 but some details on Py3 will definitely help clarify. I also personally always use from `__future__ import absolute_import`. I will update my answer with that and maybe expand my rationale in the last paragraph, but the PEPs are more detailed and clear than I will ever be ;-) – Stefano Sep 22 '15 at 16:02
  • @ninMonkey, I found an answer about py3 already so linked that. Also added a bit more rationale on the potential `attempted relative import in non-package` error. – Stefano Oct 27 '15 at 22:58
64

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).

Patrick Mevzek
  • 10,995
  • 16
  • 38
  • 54
Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • 1
    @Rafe, "look at some well written projects ..." any suggestions ? – denis Jan 06 '11 at 17:32
  • @Denis: Rietveld is Guido van Rossum's own project, so I'd imagine that'd be a good place to look (http://code.google.com/p/rietveld/). The Python standard library isn't so great, a lot of that code doesn't follow conventions. – Rafe Kettler Jan 06 '11 at 17:48
  • @Denis well it isn't. It's most written in Python. Follow the Google code link and check out the source for yourself. – Rafe Kettler Jan 07 '11 at 15:11
  • 74
    @Rafe: that part of PEP-8 is outdated, according to Guido. http://mail.python.org/pipermail/python-dev/2010-October/104476.html – Brandon Rhodes Apr 28 '11 at 20:52
  • 14
    That statement is no longer in PEP-8 at all now. It now states absolute imports are recommended, but relative imports are an acceptable alternative. – dano Aug 01 '14 at 18:33
  • [Google's Python Style Guide](http://google-styleguide.googlecode.com/svn/trunk/pyguide.html#Imports) also use absolute imports. In my experience, the only inconvenient way when using absolute imports is you could not change your projects name (top level dir name) in a easy way. – diabloneo Nov 14 '14 at 02:52
  • 7
    The problem I have with absolute imports is when using a package within another package. In my case, it's present as a git submodule. In this case, although I can import the top-level package, any packages below this one cannot be imported because they fail to find their own modules with absolute imports. Whereas if I use relative imports at this bottom level, it all just works. – davidA Mar 01 '17 at 02:40
  • Why were relative imports added when there is an "official" recommendation not to use them? – Martin Thoma Sep 10 '20 at 07:42
  • My problem with absolute imports is that when I run my test suite Python prefers to use the installed version of my package instead of the new dev version I am trying to test. I'm not totally sure that relative imports fix the problem, because imports are so complicated that I immediately forget how they work every time I learn it, but I think they work better in this case. – Ben Farmer Oct 11 '22 at 03:37
45

Relative imports not only leave you free to rename your package later without changing dozens of internal imports, but I have also had success with them in solving certain problems involving things like circular imports or namespace packages, because they do not send Python "back to the top" to start the search for the next module all over again from the top-level namespace.

Brandon Rhodes
  • 83,755
  • 16
  • 106
  • 147
  • 2
    @RafeKettler can you explain how you would use absolute imports in a package that is itself included within another package? The absolute imports will fail within the inner package because they don't know about the new top level. Relative imports continue to work. One could probably argue that the package shouldn't be nested inside another in the first place, but some code is meant to be reusable and this happens a lot. A lot of reused code isn't packaged for the public and therefore isn't provided as a separate package so ad-hoc methods such as VCS import/submodules end up being used instead – davidA Mar 01 '17 at 20:30
  • 4
    @meowsqueak I agree, some packages are not easily installable (they are not on pip, you don't want to use `python setup.py install` or `python setup.py develop` for whatever reason), in those cases I fork the source code and add it as a git submodule. When those packages use absolute imports on their own package name, their imports fail. The only solution is to use explicit relative imports. That is what should be encouraged I think. – CMCDragonkai May 02 '18 at 05:20