Skip to content
Search

Isort

lastmod 2024-10-11created 2020-12-149 edits

Automatically sorts the libraries imported in Python

Commandline Example

isort --check --diff --color test.py
  • --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:

  1. FUTURE
  2. STDLIB
  3. THIRDPARTY
  4. FIRSTPARTY
  5. 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:

python -m isort --settings-path "isort.cfg" --check --diff --color .

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:

import module  # isort:skip

or:

from xyz import (abc,  # isort:skip
                 yo,
                 hey)

To make isort skip an entire file simply add isort:skip_file to the module's doc string:

""" my_module.py
    Best module ever

   isort:skip_file
"""

import b
import a

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.

known_third_party = imgui,keyring,pygame,numpy

See also

Favorite site

author Zer0 sitemap