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.
2 Answers 2
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 groups
You can also add your own style.
I'm not a python expert, so I may be missing something, but the only import order standard I'm aware of is PEP8:
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.
Some tools such as pylint will warn you if your code breaks this suggestion.
It seems this is pretty much what you're doing already. The standard doesn't say, but sorting alphabetically within each group makes sense to me as well.
-
Yeah, I'm aware of PEP8 - unfortunately, as you mention, it's a bit ambiguous about the ordering within each of the blocks.VF1– VF12017年01月27日 16:38:26 +00:00Commented Jan 27, 2017 at 16:38
-
1Does PEP specify the order for private vs public imports? (
import _tkinter
vsimport unittest
)Stevoisiak– Stevoisiak2018年05月25日 15:21:32 +00:00Commented May 25, 2018 at 15:21
import x
andfrom x import y
statements?