ChatGPT解决这个技术问题 Extra ChatGPT

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?


C
Community

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:

Relative imports in Python 3


Guido wrote that in 2010 and it's still in the PEP? How can we trust PEPs if they are so outdated?
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.
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.
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.
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.
P
Patrick Mevzek

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


@Rafe, "look at some well written projects ..." any suggestions ?
@Denis: Rietveld is Guido van Rossum's own project, so I'd imagine that'd be a good place to look (code.google.com/p/rietveld). The Python standard library isn't so great, a lot of that code doesn't follow conventions.
@Rafe: that part of PEP-8 is outdated, according to Guido. mail.python.org/pipermail/python-dev/2010-October/104476.html
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.
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.
B
Brandon Rhodes

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.


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