I am working on a large project in python that has lots of imports.
- Some imports are system imports – these are easy, usually just absolutely imported.
- Some imports are third-party. These can have long, clunky absolute names, but clearly named single functions (requiring
from ... import
statements). Finally, some have canonical aliases (import numpy as np
). - Some imports are from my own package, which has 2 levels of heierarchy: 1 top level containing subdirectories with code.
Given all this, the most readable import scheme I could come up with is the following:
import aaa_sys
import bbb_sys
import aaa_third
from bbb_third import bb
import ccc_third as cc
import ddd_third
import .aaa_local
import .bbb_local
import ..aaa_remote.aaa_remote_module
import ..bbb_remote.bbb_remote_module
In other words, regardless of the type of import (absolute or aliasing or selective importing), I alphabetically import first the system, then third party, and finally package libraries.
Is there an industry-accepted approach to this? Something akin to Google C++ header import order.
Best Answer
If you are looking for a more detailed standard than pep8, see https://github.com/PyCQA/flake8-import-order
From their README,
The following styles are directly supported:
cryptography
- see an examplegoogle
- style described in Google Style Guidelines , see an examplesmarkets
- style asgoogle
only withimport
statements beforefrom X import ...
statements, see an exampleappnexus
- style asgoogle
only withimport
statements for packages local to your company or organisation coming afterimport
statements for third-party packages, see an exampleedited
- see an examplepycharm
- style assmarkets
only with case sensitive sorting imported namespep8
- style that only enforces groups without enforcing the order within the groupsYou can also add your own style.