[Answer]-Dot operator for import 1.7 vs 1.8 style

1👍

This is at least somewhat subjective, but in my opinion a relative import is generally better when you’re trying to import files from the same package.

If you happen to have a module named polls in the current package but also a package named polls at the top level, using polls is ambiguous to the reader–and has different meanings in old vs. new versions of Python. But using . has only one meaning to any reader or any version of Python, and there’s no way it can collide with anything else accidentally.

Also, with relative imports, you can rename your package and everything still works; with absolute, you have to edit every file. If you move the package inside another package, it may require even bigger changes.

There are also some minor reasons. If you accidentally put a package on sys.path (e.g., by running your top-level app with the current working directory set to the package), it’s usually easier to debug with relative imports. Importing yourself (and in some cases doing so implicitly with pickle or multiprocessing) is easier with relative imports.

The best reason to use the old style is if you need to be backward-compatible with Python 2.5 or earlier. (Which Django used to support, but no longer does. Although I don’t know whether or not they switched in 1.8 because that’s when they dropped enough old versions.)

Read PEP 328 for further discussion of the rationale.

Leave a comment