I am new to Python. I am developing a small project. I need to follow coding standards from starting on wards. How to use import
statements in a proper way. Now I am working on Python 2.7. If I move to 3.x are there any conflicts with absolute imports? And what is the difference between absolute and relative imports?
-
Can you please clarify what absolute and relative imports are? – Ol' Reliable Mar 27 '14 at 05:58
-
4@Ol'Reliable They are described in [PEP 328](http://legacy.python.org/dev/peps/pep-0328/). – Two-Bit Alchemist Mar 27 '14 at 06:10
2 Answers
The distinction between absolute
and relative
that's being drawn here is very similar to the way we talk about absolute and relative file paths or even URLs.
An absolute {import, path, URL} tells you exactly how to get the thing you are after, usually by specifying every part:
import os, sys
from datetime import datetime
from my_package.module import some_function
Relative {imports, paths, URLs} are exactly what they say they are: they're relative to their current location. That is, if the directory structure changes or the file moves, these may break (because they no longer mean the same thing).
from .module_in_same_dir import some_function
from ..module_in_parent_dir import other_function
Hence, absolute imports are preferred for code that will be shared.
I was asked in comments to provide an example of how from __future__ import absolute_import
ties into this, and how it is meant to be used. In trying to formulate this example, I realized I couldn't quite explain its behavior either, so I asked a new question. This answer gives a code sample showing a correctly working implementation of from __future__ import absolute_import
, where it actually resolves an ambiguity.
The accepted answer goes into more detail about why this works the way it does, including a discussion of the confusing wording of the Python 2.5 changelog. Essentially, the scope of this directive (and by extension the distinction between absolute and relative imports in Python) is very, very narrow. If you find yourself needing these distinctions to make your code work, you're probably better off renaming your local module if at all possible.

- 1
- 1

- 17,966
- 6
- 47
- 82
-
That's what I'd have thought too. But if that's the case, why do imports of the latter form still work when I have `from __future__ import (absolute_import)`? – orome Nov 14 '15 at 20:38
-
3@raxacoricofallapatorius Say you have a local module named `string`. You open an interpreter and issue `import string`. Python 2.5 would give you the local module. Python 2.7+ would give you the [string](https://docs.python.org/2/library/string.html) library. That future directive shifts Python 2.5 into the 2.7 default behavior. The dotted forms are explicitly relative, so there is no ambiguity possible with the standard library. Hence, they always work the same. [More](https://docs.python.org/2.5/whatsnew/pep-328.html) – Two-Bit Alchemist Nov 16 '15 at 05:29
-
1Ah I see, `from __future__ absolute_import` prohibits *implicit* relative imports (explicit ones are fine). Correct? – orome Nov 16 '15 at 13:14
-
3@raxacoricofallapatorius I think even implicit ones are fine under that directive. All it does is cause Python to prefer the absolute version when there is a conflict -- when an import statement could validly be interpreted as either relative (local module) or absolute (standard library). In other words, it prevents you from accidentally overshadowing parts of the Python standard library by creating directories on `sys.path` of the same name, similar to the way naming a variable `list` overshadows the built-in `list` function. – Two-Bit Alchemist Nov 16 '15 at 16:59
-
@raxacoricofallapatorius I got Python 2.5 installed to test this and potentially write an example, and turns out I'm not as clear or sure what is happening as I thought. I have [asked a new question](http://stackoverflow.com/q/33743880/2588818) about this particular behavior that you might be interested in following. – Two-Bit Alchemist Nov 16 '15 at 20:19
Imports should usually be on separate lines:
Yes: import os
import sys
No: import sys, os
It's okay to say this though:
from subprocess import Popen, PIPE
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Imports should be grouped in the following order:
- Standard library imports.
- Related third party imports.
- Local application/library specific imports.
- You should put a blank line between each group of imports.
As per Pep8 :- Absolute imports are recommended, as they are usually more readable and tend to be better behaved (or at least give better error messages) if the import system is incorrectly configured (such as when a directory inside a package ends up on sys.path):
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example
However, explicit relative imports are an acceptable alternative to absolute imports, especially when dealing with complex package layouts where using absolute imports would be unnecessarily verbose:
from . import sibling
from .sibling import example
Standard library code should avoid complex package layouts and always use absolute imports.
Implicit relative imports should never be used and have been removed in Python 3.
When importing a class from a class-containing module, it's usually okay to spell this:
from myclass import MyClass
from foo.bar.yourclass import YourClass
If this spelling causes local name clashes, then spell them explicitly:
import myclass
import foo.bar.yourclass
and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".
Wildcard imports (from <module> import *
) should be avoided, as they make it unclear which names are present in the namespace, confusing both readers and many automated tools. There is one defensible use case for a wildcard import, which is to republish an internal interface as part of a public API (for example, overwriting a pure Python implementation of an interface with the definitions from an optional accelerator module and exactly which definitions will be overwritten isn't known in advance).
-
1To avoid long absolute import references and also avoid relative references, I have simply used python function definition, eg >>> mylog = parentdir.subdir.utils.logger.Logger; mylog.warning_log('oops') – AnneTheAgile Oct 02 '19 at 15:38