Top Related Projects
The uncompromising Python code formatter
A formatter for Python files
A tool that automatically formats Python code to conform to the PEP 8 style guide.
The strictest and most opinionated python linter ever!
Quick Overview
isort is a Python library that automatically sorts and formats Python import statements. It is designed to help maintain consistent and readable code by ensuring that imports are organized in a standardized way.
Pros
- Automatic Sorting: isort automatically sorts import statements based on a set of predefined rules, ensuring consistent formatting across a codebase.
- Configurable: isort provides a wide range of configuration options, allowing developers to customize the sorting and formatting behavior to suit their project's needs.
- Integrates with IDEs: isort can be integrated with popular IDEs like PyCharm, Visual Studio Code, and Sublime Text, making it easy to use within the development environment.
- Supports Multiple Python Versions: isort is compatible with a wide range of Python versions, from 2.7 to the latest 3.x releases.
Cons
- Potential Conflicts with Other Formatters: isort may not always play nicely with other code formatting tools, such as Black or Autopep8, which can lead to conflicts and unexpected behavior.
- Steep Learning Curve: While isort is relatively straightforward to use, its extensive configuration options can make it challenging for new users to fully understand and optimize its usage.
- Potential Performance Impact: Depending on the size and complexity of the codebase, running isort on large projects may have a noticeable performance impact, especially during continuous integration or deployment workflows.
- Limited Support for Non-Python Languages: isort is primarily focused on Python and may not provide the same level of support for other programming languages that may be used in a project.
Code Examples
Here are a few examples of how to use isort in your Python code:
- Sorting Imports Automatically:
import os
import sys
from datetime import datetime
from typing import List
import numpy as np
import pandas as pd
After running isort, the imports will be sorted as follows:
import os
import sys
from datetime import datetime
from typing import List
import numpy as np
import pandas as pd
- Configuring isort:
# .isort.cfg
[settings]
profile = black
known_first_party = my_project
known_third_party = numpy,pandas
This configuration file tells isort to use the "black" profile, which aligns with the Black code formatter, and specifies the known first-party and third-party modules for the project.
- Integrating isort with Git:
# Add the following to your .git/hooks/pre-commit file
#!/bin/bash
isort .
git add .
This Git hook will automatically run isort on your staged files before each commit, ensuring that your import statements are properly formatted.
Getting Started
To get started with isort, follow these steps:
- Install isort using pip:
pip install isort
- Run isort on your Python files:
isort my_python_file.py
- Customize isort's behavior by creating a configuration file (
.isort.cfg
) in your project's root directory:
[settings]
profile = black
known_first_party = my_project
known_third_party = numpy,pandas
- Integrate isort into your development workflow, such as by adding a Git hook or configuring it in your IDE.
For more detailed information and advanced usage, please refer to the isort documentation.
Competitor Comparisons
The uncompromising Python code formatter
Pros of Black
- Opinionated and deterministic formatting, ensuring consistent code style across projects
- Faster execution time for large codebases
- Integrates well with popular IDEs and text editors
Cons of Black
- Less configurable, with fewer options for customization
- May produce unexpected formatting in some edge cases
- Does not sort imports or handle import organization
Code Comparison
Black formatting:
def long_function_name(
var_one: int, var_two: str, var_three: float, var_four: bool
) -> None:
print(f"{var_one}, {var_two}, {var_three}, {var_four}")
isort formatting:
from module1 import func1
from module2 import func2, func3
import module3
import module4
def example_function():
pass
isort focuses on organizing and sorting imports, while Black handles overall code formatting. isort offers more customization options and specifically targets import statements, whereas Black aims for consistent, opinionated formatting across entire Python files. Both tools can be used together in a development workflow to achieve well-organized and consistently formatted code.
A formatter for Python files
Pros of yapf
- More comprehensive code formatting, handling entire file structure
- Highly configurable with style options
- Supports multiple programming styles (Google, PEP8, Facebook)
Cons of yapf
- Can be slower for large codebases
- May make more aggressive changes to code layout
- Learning curve for configuration options
Code comparison
isort example:
from z import y
import x
from a import b
yapf example:
import x
from a import b
from z import y
def long_function_name(
var_one, var_two, var_three, var_four):
print(var_one)
Key differences
isort focuses specifically on import sorting, while yapf is a more comprehensive code formatter. isort is generally faster and makes fewer changes to existing code, but yapf offers more extensive formatting options.
isort is ideal for projects that only need import sorting, while yapf is better suited for teams wanting consistent formatting across entire codebases. Both tools can be integrated into development workflows and CI/CD pipelines.
The choice between isort and yapf depends on the specific needs of the project and team preferences for code style enforcement.
A tool that automatically formats Python code to conform to the PEP 8 style guide.
Pros of autopep8
- Broader scope: Fixes a wide range of PEP 8 style issues beyond import sorting
- More customizable: Offers numerous configuration options for fine-tuning
- In-place file modification: Can directly modify files, saving time
Cons of autopep8
- Less specialized: May not handle import sorting as effectively as isort
- Potentially slower: Broader scope can lead to longer processing times
- Less focus on import organization: Doesn't offer advanced import grouping features
Code Comparison
isort:
import sys
from os import path
import requests
autopep8:
import sys
from os import path
import requests
def example():
pass
Summary
While isort specializes in organizing and sorting imports, autopep8 offers a more comprehensive approach to PEP 8 compliance. isort excels at import management, providing advanced sorting and grouping features. autopep8, on the other hand, addresses a wider range of style issues but may not handle imports as meticulously. The choice between the two depends on whether you need focused import sorting (isort) or broader PEP 8 compliance (autopep8).
The strictest and most opinionated python linter ever!
Pros of wemake-python-styleguide
- Comprehensive set of over 900 style checks for Python code
- Highly configurable with options to enable/disable specific rules
- Integrates well with various CI/CD pipelines and code editors
Cons of wemake-python-styleguide
- Can be overly strict and opinionated, potentially leading to excessive warnings
- Steeper learning curve due to the large number of rules and configurations
- May slow down the development process for teams not used to strict style guidelines
Code Comparison
isort:
from z import y
import x
print(x, y)
wemake-python-styleguide:
import x
from z import y
print(x, y)
The main difference in this example is that wemake-python-styleguide enforces a specific import order (standard library imports first, then third-party, then local), while isort focuses primarily on sorting imports alphabetically within their respective groups.
While isort is specifically designed for import sorting, wemake-python-styleguide covers a much broader range of style checks. isort is generally easier to adopt and less intrusive, making it a good choice for teams looking to standardize import ordering. wemake-python-styleguide, on the other hand, is better suited for teams or projects that require strict adherence to a comprehensive set of style guidelines.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Read Latest Documentation - Browse GitHub Code Repository
isort your imports, so you don't have to.
isort is a Python utility / library to sort imports alphabetically and automatically separate into sections and by type. It provides a command line utility, Python library and plugins for various editors to quickly sort all your imports. It requires Python 3.8+ to run but supports formatting Python 2 code too.
- Try isort now from your browser!
- Using black? See the isort and black compatibility guide.
- isort has official support for pre-commit!
Before isort:
from my_lib import Object
import os
from my_lib import Object3
from my_lib import Object2
import sys
from third_party import lib15, lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14
import sys
from __future__ import absolute_import
from third_party import lib3
print("Hey")
print("yo")
After isort:
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")
Installing isort
Installing isort is as simple as:
pip install isort
Using isort
From the command line:
To run on specific files:
isort mypythonfile.py mypythonfile2.py
To apply recursively:
isort .
If globstar
is enabled, isort .
is equivalent to:
isort **/*.py
To view proposed changes without applying them:
isort mypythonfile.py --diff
Finally, to atomically run isort against a project, only applying changes if they don't introduce syntax errors:
isort --atomic .
(Note: this is disabled by default, as it prevents isort from running against code written using a different version of Python.)
From within Python:
import isort
isort.file("pythonfile.py")
or:
import isort
sorted_code = isort.code("import b\nimport a\n")
Installing isort's for your preferred text editor
Several plugins have been written that enable to use isort from within a variety of text-editors. You can find a full list of them on the isort wiki. Additionally, I will enthusiastically accept pull requests that include plugins for other text editors and add documentation for them as I am notified.
Multi line output modes
You will notice above the "multi_line_output" setting. This setting defines how from imports wrap when they extend past the line_length limit and has 12 possible settings.
Indentation
To change the how constant indents appear - simply change the indent property with the following accepted formats:
- Number of spaces you would like. For example: 4 would cause standard 4 space indentation.
- Tab
- A verbatim string with quotes around it.
For example:
" "
is equivalent to 4.
For the import styles that use parentheses, you can control whether or
not to include a trailing comma after the last import with the
include_trailing_comma
option (defaults to False
).
Intelligently Balanced Multi-line Imports
As of isort 3.1.0 support for balanced multi-line imports has been added. With this enabled isort will dynamically change the import length to the one that produces the most balanced grid, while staying below the maximum import length defined.
Example:
from __future__ import (absolute_import, division,
print_function, unicode_literals)
Will be produced instead of:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
To enable this set balanced_wrapping
to True
in your config or pass
the -e
option into the command line utility.
Custom Sections and Ordering
isort provides configuration options to change almost every aspect of how imports are organized, ordered, or grouped together in sections.
Click here for an overview of all these options.
Skip processing of imports (outside of configuration)
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
Adding or removing an import from multiple files
isort can be ran or configured to add / remove imports automatically.
Using isort to verify code
The --check-only
option
isort can also be used to verify that code is correctly formatted
by running it with -c
. Any files that contain incorrectly sorted
and/or formatted imports will be outputted to stderr
.
isort **/*.py -c -v
SUCCESS: /home/timothy/Projects/Open_Source/isort/isort_kate_plugin.py Everything Looks Good!
ERROR: /home/timothy/Projects/Open_Source/isort/isort/isort.py Imports are incorrectly sorted.
One great place this can be used is with a pre-commit git hook, such as this one by @acdha:
https://gist.github.com/acdha/8717683
This can help to ensure a certain level of code quality throughout a project.
Git hook
isort provides a hook function that can be integrated into your Git pre-commit script to check Python code before committing.
Setuptools integration
Upon installation, isort enables a setuptools
command that checks
Python files declared by your project.
Spread the word
Place this badge at the top of your repository to let others know your project uses isort.
For README.md:
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)
Or README.rst:
.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336
:target: https://pycqa.github.io/isort/
Security contact information
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
Why isort?
isort simply stands for import sort. It was originally called "sortImports" however I got tired of typing the extra characters and came to the realization camelCase is not pythonic.
I wrote isort because in an organization I used to work in the manager came in one day and decided all code must have alphabetically sorted imports. The code base was huge - and he meant for us to do it by hand. However, being a programmer - I'm too lazy to spend 8 hours mindlessly performing a function, but not too lazy to spend 16 hours automating it. I was given permission to open source sortImports and here we are :)
Get professionally supported isort with the Tidelift Subscription
Professional support for isort is available as part of the Tidelift Subscription. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools.
Thanks and I hope you find isort useful!
~Timothy Crosley
Top Related Projects
The uncompromising Python code formatter
A formatter for Python files
A tool that automatically formats Python code to conform to the PEP 8 style guide.
The strictest and most opinionated python linter ever!
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot