Isort
lastmod 2024-10-11created 2020-12-149 edits
Automatically sorts the libraries imported in Python
Commandline Example
-
--check: Only checks for errors without modifying files. -
--diff: Prints the changes in diff format. -
--color: Applies color to terminal output.
Default Sections Order
The default sort order is as follows:
- FUTURE
- STDLIB
- THIRDPARTY
- FIRSTPARTY
- LOCALFOLDER
An example:
from __future__ import absolute_import
import os
import sys
from third_party import (lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8,
lib9, lib10, lib11, lib12, lib13, lib14, lib15)
from my_lib import Object, Object2, Object3
print("Hey")
print("yo")
Configuration
Example
# isort configuration
[isort]
py_version = 39
profile = black
src_paths = recc,test,tester
skip_gitignore = True
# sections=FUTURE,STDLIB,FIRSTPARTY,THIRDPARTY,LOCALFOLDER
# import_heading_future = Futures
# import_heading_stdlib = Standard Libraries
# import_heading_thirdparty = Third-party Libraries
# import_heading_firstparty = First-party Libraries
# import_heading_localfolder = Local Libraries
To run:
Inline ignore
To make isort ignore a single import simply add a comment at the end of the import line containing the text isort:skip:
or:
To make isort skip an entire file simply add isort:skip_file to the module's doc string:
Troubleshooting
THIRDPARTY libraries sorted into the LOCALFOLDER position
Sorting produces the following:
# -*- coding: utf-8 -*-
import os
from typing import Any, Callable, Coroutine, List, Mapping
from reccd.daemon.daemon_client import DaemonClient
from type_serialize import deserialize
from answer_plugin_vms.packet.event_category import EventCategory
from answer_plugin_vms.storage.local_storage import LocalStorage
from numpy import ndarray
Since numpy is THIRDPARTY, you would expect it on line 6, but it appears on line 11.
This can happen when a subdirectory of LOCALFOLDER contains the name of a THIRDPARTY library. So it is best to avoid such folder names.
Alternatively, declare it explicitly as THIRDPARTY.
See also
Favorite site
Pages that link here