| 1 |
.. -*- mode: rst -*- |
| 2 |
.. vi: set ft=rst sts=4 ts=4 sw=4 et tw=79: |
| 3 |
|
| 4 |
.. _chap_design_python_imports: |
| 5 |
|
| 6 |
************************ |
| 7 |
Python import statements |
| 8 |
************************ |
| 9 |
|
| 10 |
.. topic:: Specification scope and status |
| 11 |
|
| 12 |
This specification describes the current (albeit incomplete) implementation. |
| 13 |
|
| 14 |
The following rules apply to any ``import`` statement in the code base: |
| 15 |
|
| 16 |
- All imports *must* be absolute, unless they import individual pieces of an integrated code component that is only split across several source code files for technical or organizational reasons. |
| 17 |
|
| 18 |
- Imports *must* be placed at the top of a source file, unless there is a |
| 19 |
specific reason not to do so (e.g., delayed import due to performance |
| 20 |
concerns, circular dependencies). If such a reason exists, it *must* |
| 21 |
be documented by a comment at the import statement. |
| 22 |
|
| 23 |
- There *must* be no more than one import per line. |
| 24 |
|
| 25 |
- Multiple individual imports from a single module *must* follow the pattern:: |
| 26 |
|
| 27 |
from <module> import ( |
| 28 |
symbol1, |
| 29 |
symbol2, |
| 30 |
) |
| 31 |
|
| 32 |
Individual imported symbols *should* be sorted alphabetically. The last symbol |
| 33 |
line *should* end with a comma. |
| 34 |
|
| 35 |
- Imports from packages and modules *should* be grouped in categories like |
| 36 |
|
| 37 |
- Standard library packages |
| 38 |
|
| 39 |
- 3rd-party packages |
| 40 |
|
| 41 |
- DataLad core (absolute imports) |
| 42 |
|
| 43 |
- DataLad extensions |
| 44 |
|
| 45 |
- DataLad core ("local" relative imports) |
| 46 |
|
| 47 |
Sorting imports can be aided by https://github.com/PyCQA/isort (e.g. ``python -m isort -m3 --fgw 2 --tc <filename>``). |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
Examples |
| 52 |
======== |
| 53 |
|
| 54 |
:: |
| 55 |
|
| 56 |
from collections import OrderedDict |
| 57 |
import logging |
| 58 |
import os |
| 59 |
|
| 60 |
from datalad.utils import ( |
| 61 |
bytes2human, |
| 62 |
ensure_list, |
| 63 |
ensure_unicode, |
| 64 |
get_dataset_root as gdr, |
| 65 |
) |
| 66 |
|
| 67 |
In the `datalad/submodule/tests/test_mod.py` test file demonstrating an "exception" to absolute imports |
| 68 |
rule where test files are accompanying corresponding files of the underlying module:: |
| 69 |
|
| 70 |
import os |
| 71 |
|
| 72 |
from datalad.utils import ensure_list |
| 73 |
|
| 74 |
from ..mod import func1 |
| 75 |
|
| 76 |
from datalad.tests.utils_pytest import assert_true |