The python style guide suggests to group imports like this:
Imports should be grouped in the following order:
- standard library imports
- related third party imports
- local application/library specific imports
However, it does not mention anything how the two different ways of imports should be laid out:
from foo import bar
import foo
There are multiple ways to sort them (let's assume all those import belong to the same group):
first
from..import
, thenimport
from g import gg from x import xx import abc import def import x
first
import
, thenfrom..import
import abc import def import x from g import gg from x import xx
alphabetic order by module name, ignoring the kind of import
import abc import def from g import gg import x from xx import xx
PEP8 does not mention the preferred order for this and the "cleanup imports" features some IDEs have probably just do whatever the developer of that feature preferred.
I'm looking for another PEP clarifying this or a relevant comment/email from the BDFL (or another Python core developer). Please don't post subjective answers stating your own preference.
The PEP 8 says nothing about it indeed. There's no convention for this point, and it doesn't mean the Python community need to define one absolutely. A choice can be better for a project but the worst for another... It's a question of preferences for this, since each solutions has pro and cons. But if you want to follow conventions, you have to respect the principal order you quoted:
For example, Google recommend in this page that import should be sorted lexicographically, in each categories (standard/third parties/yours). But at Facebook, Yahoo and whatever, it's maybe another convention...
According to the CIA's internal coding conventions (part of the WikiLeaks Vault 7 leak), python imports should be grouped into three groups:
Imports should be ordered lexicographically within these groups, ignoring case:
All
import x
statements should be sorted by the value ofx
and allfrom x import y
statements should be sorted by the value ofx
in alphabetical order and the sorted groups offrom x import y
statements must follow the sorted group ofimport x
statements.Imports are generally sorted alphabetically and described in various places beside PEP 8.
Alphabetically sorted modules are quicker to read and searchable. After all python is all about readability. Also It is easier to verify that something is imported, and avoids duplicated imports
There is nothing available in PEP 8 regarding sorting.So its all about choice what you use.
According to few references from reputable sites and repositories also popularity, Alphabetical ordering is the way.
for eg like this:
OR
Reddit official repository also states that, In general PEP-8 import ordering should be used. However there are a few additions which is
References:
PS: the isort utility automatically sorts your imports.