isort is a Python utility / library to sort imports alphabetically, and automatically separated into sections and by type.

Overview

isort - isort your imports, so you don't have to.


PyPI version Test Status Lint Status Code coverage Status License Join the chat at https://gitter.im/timothycrosley/isort Downloads Code style: black Imports: isort DeepSource


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 separated 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.6+ to run but supports formatting Python 2 code too.

Example Usage

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

Install isort with requirements.txt support:

pip install isort[requirements_deprecated_finder]

Install isort with Pipfile support:

pip install isort[pipfile_deprecated_finder]

Install isort with both formats support:

pip install isort[requirements_deprecated_finder,pipfile_deprecated_finder]

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.

See a complete guide here.

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.

More info here.

Setuptools integration

Upon installation, isort enables a setuptools command that checks Python files declared by your project.

More info here.

Spread the word

Imports: isort

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

Comments
  • isort does not skip files

    isort does not skip files

    Describe the bug

    isort does not respect skip and skip_glob configuration options.

    To Reproduce

    Steps to reproduce the behavior:

    1. Create file.py with the following content:
      import os, \
          sys
      
    2. Create .isort.cfg with the following content:
      [settings]
      skip_glob = file.py
      
    3. Run isort file.py.
    4. Open file.py and check out it's content to become:
      import os
      import sys
      

    Expected behavior

    A file.py is skipped and is not touched.

    Screenshots

    Environment (please complete the following information):

    • OS: Linux
    • Python version: 3.7.2
    • isort version: 4.3.11

    Additional context

    isort 4.3.10 is working correctly. Issue can be reproduced with skip option as well.

    bug 
    opened by nickgashkov 29
  • skip statements

    skip statements

    Some statements need to be nested within imports, is there a way for isort to ignore them?

    Here's the motivating example:

    import matplotlib
    matplotlib.use('Agg')  # isort:skip
    import matplotlib.pyplot as plt
    

    the use Agg must be called before the plt import. isort:skip doesn't work here.

    enhancement 
    opened by simonzack 29
  • Interopability with black

    Interopability with black

    Hey, Timothy! Thanks for isort, it's a very useful project.

    I made an opinionated formatter, Black. Quite a few of my users are also isort users. That's great, I don't want to have to perform import sorting in Black. However, there's a small issue.

    None of isort's multiline modes fits what Black is doing. Black wraps lines like this:

    • try to fit everything in one line; if you can't then
    • indent the contents of the parens one level and try to fit those in one line; if you can't then
    • explode one element per line.

    The second step in Black's algorithm is like your mode 5, and the third is like mode 3. I'd like to create a pull request for isort to introduce mode 8 (5+3) that does what Black does in this scenario. This would enable Black and isort to co-exist and keep consistent import styling.

    Would you accept such pull request?

    (I initially wrote this on Twitter but this belongs here better.)

    enhancement ongoing black 
    opened by ambv 28
  • isort behavior different on linux vs osx even with config

    isort behavior different on linux vs osx even with config

    on OSX:

    web on  fox-295 [⇡$!] via 🐍 3.6.4 took 2s
    ➜ pipenv run isort --recursive --check-only server
    ERROR: /Users/ahonnecke/Code/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py Imports are incorrectly sorted.
    ERROR: /Users/ahonnecke/Code/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py Imports are incorrectly sorted.
    
    
    web on  fox-295 [⇡$!] via 🐍 3.6.4
    ➜ head -n16 /Users/ahonnecke/Code/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py
    import json
    import os
    from time import sleep
    from unittest.mock import MagicMock
    
    from django.test import TestCase
    
    from wiremock.constants import Config
    from wiremock.resources.mappings import Mapping
    from wiremock.resources.mappings.resource import Mappings
    from wiremock.server import WireMockServer
    
    
    from assets.models import Ledger
    from dad.configuration import PortfolioManagerConfiguration
    from portfolio_manager.models import LedgerAddress, Portfolio
    
    web on  fox-295 [⇡$!] via 🐍 3.6.4
    ➜ head -n16 /Users/ahonnecke/Code/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py
    import json
    import os
    from time import sleep
    from unittest.mock import MagicMock
    
    from django.test import TestCase
    
    from wiremock.constants import Config
    from wiremock.resources.mappings import Mapping
    from wiremock.resources.mappings.resource import Mappings
    from wiremock.server import WireMockServer
    
    
    from assets.models import Ledger
    from dad.configuration import PortfolioManagerConfiguration
    from portfolio_manager.wallets.ledger_client import LedgerClient
    
    web on  fox-295 [⇡$!] via 🐍 3.6.4
    ➜ pipenv run isort --recursive --check-only server
    ERROR: /Users/ahonnecke/Code/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py Imports are incorrectly sorted.
    ERROR: /Users/ahonnecke/Code/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py Imports are incorrectly sorted.
    
    web on  fox-295 [⇡$!] via 🐍 3.6.4 took 2s
    ➜ pipenv run isort --recursive server
    Fixing /Users/ahonnecke/Code/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py
    Fixing /Users/ahonnecke/Code/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py
    Skipped 26 files
    
    web on  fox-295 [⇡$!] via 🐍 3.6.4 took 2s
    ➜ head -n16 /Users/ahonnecke/Code/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py
    import json
    import os
    from time import sleep
    from unittest.mock import MagicMock
    
    from django.test import TestCase
    
    from wiremock.constants import Config
    from wiremock.resources.mappings import Mapping
    from wiremock.resources.mappings.resource import Mappings
    from wiremock.server import WireMockServer
    
    from assets.models import Ledger
    from dad.configuration import PortfolioManagerConfiguration
    from portfolio_manager.wallets.ledger_client import LedgerClient
    from util.security import create_user, get_token_for_user
    
    web on  fox-295 [⇡$!] via 🐍 3.6.4
    ➜ head -n16 /Users/ahonnecke/Code/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py
    import json
    import os
    from time import sleep
    from unittest.mock import MagicMock
    
    from django.test import TestCase
    
    from wiremock.constants import Config
    from wiremock.resources.mappings import Mapping
    from wiremock.resources.mappings.resource import Mappings
    from wiremock.server import WireMockServer
    
    from assets.models import Ledger
    from dad.configuration import PortfolioManagerConfiguration
    from portfolio_manager.models import LedgerAddress, Portfolio
    from util.security import create_client_user, get_token_for_user
    

    Cloud based CI platform (Circle CI / ubuntu)

    [email protected]:~/project/repos/web$ pipenv run isort --recursive --check-only server
    ERROR: /home/circleci/project/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py Imports are incorrectly sorted.
    ERROR: /home/circleci/project/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py Imports are incorrectly sorted.
    
    [email protected]:~/project/repos/web$ cp /home/circleci/project/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py /home/circleci/project/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py.bak
    
    [email protected]:~/project/repos/web$ cp /home/circleci/project/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py /home/circleci/project/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py.bak
    
    [email protected]:~/project/repos/web$ pipenv run isort --recursive server
    Fixing /home/circleci/project/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py
    Fixing /home/circleci/project/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py
    Skipped 26 files
    [email protected]:~/project/repos/web$ diff /home/circleci/project/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py /home/circleci/project/repos/web/server/portfolio_manager/graphql/tests/test_ledger_addresses_query.py.bak
    8,12d7
    < from wiremock.constants import Config
    < from wiremock.resources.mappings import Mapping
    < from wiremock.resources.mappings.resource import Mappings
    < from wiremock.server import WireMockServer
    <
    17a13,16
    > from wiremock.constants import Config
    > from wiremock.resources.mappings import Mapping
    > from wiremock.resources.mappings.resource import Mappings
    > from wiremock.server import WireMockServer
    [email protected]:~/project/repos/web$ diff /home/circleci/project/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py /home/circleci/project/repos/web/server/portfolio_manager/wallets/test_supported_ledgers.py.bak
    8,12d7
    < from wiremock.constants import Config
    < from wiremock.resources.mappings import Mapping
    < from wiremock.resources.mappings.resource import Mappings
    < from wiremock.server import WireMockServer
    <
    17a13,16
    > from wiremock.constants import Config
    > from wiremock.resources.mappings import Mapping
    > from wiremock.resources.mappings.resource import Mappings
    > from wiremock.server import WireMockServer
    [email protected]:~/project/repos/web$ pipenv run isort --recursive --check-only server
    Skipped 26 files
    

    isort

    [settings]
    known_django=django
    sections=FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER
    

    TLDR, isort requires a different number of newlines on ubuntu.

    repo_needed 
    opened by ahonnecke 23
  • Add configuration to ensure a newline before each comment

    Add configuration to ensure a newline before each comment

    This adds a ensure_newline_before_comments configuration that matches the format that black imposes (for better or worse) and allows isort to be used with black without any thrashing/conflicts with regards to blank lines before comments.

    Should help address https://github.com/psf/black/issues/251

    opened by FuegoFro 18
  • ast and others not considered standard lib

    ast and others not considered standard lib

    Hi Tim,

    Upgrading from 4.2.5 to 4.2.8, it seems that isort now does not recognize ast as a standard library anymore. We can see it's doc here in standard library so I think it really should be considered stdlib :/

    What do you think?

    bug 
    opened by pawamoy 17
  • How to make isort black compatible. Original Question: isort conflicts with black?

    How to make isort black compatible. Original Question: isort conflicts with black?

    Hi.

    I experience that black and isort undo eachothers changes when working on some of my files.

    I am using the following two first steps in my .pre-commit-config.yaml:

    repos:
      - repo: https://github.com/psf/black
        rev: 20.8b1
        hooks:
          - id: black
    
      - repo: https://github.com/pycqa/isort
        rev: 5.5.4
        hooks:
          - id: isort
    

    When I run pre-commit run --all-files, both black and isort report they are making changes. The changes result to the following formatting in my file configs.py:

    from datetime import date
    
    from cost_categories import (applsj, asjdfsi, bananana, sdjffsd, sjdifjsl,
                                 sjdil, yoyoyoyoy)
    from library_user import User
    

    However, if I remove the isort-hook from the yaml file, the conflict stops. Then, I get the following output (as dictated by black alone):

    from datetime import date
    
    from cost_categories import (
        applsj,
        asjdfsi,
        bananana,
        sdjffsd,
        sjdifjsl,
        sjdil,
        yoyoyoyoy,
    )
    from library_user import User
    

    How should I approach this? Am I using some wrong revision?

    question documentation 
    opened by tordbb 16
  • skips are not honored since isort 5.9.x

    skips are not honored since isort 5.9.x

    I'm using isort with my project for some time now, thank you for this project !

    Everything was working well with 5.8.0 but with 5.9.0 I have the error

    OSError: [Errno 7] Argument list too long: 'git'
    

    And with the version 5.9.1, extend_skip and skip_gitignore are not honored and isort goes into my venv folder where it shouldn't go.

    Thank you for looking into this

    bug repo_needed 
    opened by pums974 15
  • Add `multi_line_output` mode for more compact formatting

    Add `multi_line_output` mode for more compact formatting

    Could we add a mode similar to 0/grid mode, but that uses the fixed indent width for subsequent lines? Mode 0 looks like this:

    from third_party import (lib1, lib2, lib3,
                             lib4, lib5, ...)
    

    I would like this (where indent=2):

    from third_party import (lib1, lib2, lib3,
      lib4, lib5, ...)
    

    This would be more compact, and can reduce line count. I would be happy to attempt a PR; pointers on where to look would be welcome. isort has been a great improvement to my workflow; thank you for building it!

    enhancement help wanted good first issue 
    opened by gwk 15
  • [regression] Inconsistent results on travis-ci

    [regression] Inconsistent results on travis-ci

    After the last release I started to get inconsistent results on travis again (python3).

    I cannot replicate and fix the issues.

    I opened this issue even though I don't have much details to offer, hoping that if more people are experiencing the same problem they will help to debug, for now I will try to pin the test requirements to the previous stable version.

    bug 
    opened by nemesisdesign 15
  • First-party library (incorrectly?) detected as third-party depending on working directory

    First-party library (incorrectly?) detected as third-party depending on working directory

    I cannot post my a fully-contained working environment here, but this is my example code, and maybe it's enough to reproduce or at least understand the issue.

    This is /home/bers/myproj/myproj/tool/bug.py:

    import os
    
    import isort
    
    import myproj
    
    
    def _test():
        code = isort.code(open(__file__).read(), import_heading_thirdparty="3rd")
        print(code[: code.find("\n\n\ndef")] + "\n")
    
    
    print("correct:")
    os.chdir("/home/bers/myproj/myproj")
    _test()
    
    print("incorrect:")
    os.chdir("/home/bers/myproj/myproj/tool")
    _test()
    

    What this outputs is this:

    correct:
    import os
    
    # 3rd
    import isort
    
    import myproj
    
    incorrect:
    import os
    
    # 3rd
    import myproj
    import isort
    

    So you see that isort detects myproj as a 3rd-party library depending on the working directory - is this intended?

    It may be relevant that I usually do pip install -e . from /home/bers/myproj when setting up environments - this is what makes import myproj possible from within /home/bers/myproj/myproj/tool/bug.py.

    question 
    opened by bersbersbers 14
  • Fix re-export sorter

    Fix re-export sorter

    PR changes

    1. Fixes a big where the line would be duplicated rather than sorted

    2. Allows for unbracketed tuples to be sorted

    3. Allows sets of re-exports to be sorted

    4. Allows literals to be sorted even if there are no spaces between the variable name and the literal

    5. Renames numerous variables tied to the re-exporter for clarity

    Regarding point 4

    Previously, isort would not be able to sort the following code:

    my_list=[2, 3, 1]
    

    Now, it sorts it like so:

    my_list = [1, 2, 3]
    

    Related issues

    Closes #1887. Closes #1971. Closes #2037.

    opened by parafoxia 1
  • `isort` does not respect `# pylint: disable-next`

    `isort` does not respect `# pylint: disable-next`

    Given an import section as follow:

        # pylint: disable-next=no-name-in-module
        from C import D
        # pylint: disable-next=no-name-in-module
        from A import B
    

    isort will reorder them as follows, breaking the pylint disable

        # pylint: disable-next=no-name-in-module
        # pylint: disable-next=no-name-in-module
        from A import B
        from C import D
    
    opened by labrys 0
  • inconsistencies of known_first_party and --resolve-all-configs argument

    inconsistencies of known_first_party and --resolve-all-configs argument

    I have a repo with this tree:

    directory_root
    
        packageA
            setup.cfg
            module1.py
            module2.py
    
        packageB
            module3.py
    

    With packageA/module1.py having the following contents:

    import module2
    import packageB
    import numpy
    import os
    

    and packageA/setup.cfg having the following contents:

    [isort]
    known_first_party = bla
    

    If I run isort with: python -m isort --verbose --check-only packageA/module1.py packageA/module2.py packageB/module3.py I get the following output:

    
                     _                 _
                    (_) ___  ___  _ __| |_
                    | |/ _/ / _ \/ '__  _/
                    | |\__ \/\_\/| |  | |_
                    |_|\___/\___/\_/   \_/
    
          isort your imports, so you don't have to.
    
                        VERSION 5.11.2
    
    else-type place_module for module2 returned FIRSTPARTY
    else-type place_module for packageB returned THIRDPARTY
    else-type place_module for numpy returned THIRDPARTY
    else-type place_module for os returned STDLIB
    ERROR: /directory_root/packageA/module1.py Imports are incorrectly sorted and/or formatted.
    SUCCESS: /directory_root/packageA/module2.py Everything Looks Good!
    SUCCESS: /directory_root/packageB/module3.py Everything Looks Good!
    

    which is what I expected. So if I run isort without --check-only option, the original packageA/module1.py file is reformatted to:

    import os
    
    import numpy
    import packageB
    
    import module2
    

    However, I want to start having support for multiple config files in a single isort run, so I have to use the --resolve-all-configs argument: python -m isort --verbose --resolve-all-configs --check-only packageA/module1.py packageA/module2.py packageB/module3.py which gives me the following output:

                     _                 _
                    (_) ___  ___  _ __| |_
                    | |/ _/ / _ \/ '__  _/
                    | |\__ \/\_\/| |  | |_
                    |_|\___/\___/\_/   \_/
    
          isort your imports, so you don't have to.
    
                        VERSION 5.11.2
    
    ./packageA/setup.cfg used for file packageA/module1.py
    ERROR: /directory_root/packageA/module1.py Imports are incorrectly sorted and/or formatted.
    ./packageA/setup.cfg used for file packageA/module2.py
    default used for file packageB/module3.py
    

    First Question: Why is the verbose debug information different when using the --resolve-all-configs argument? The else-type place_module for <some_import> returned <SECTION_NAME> messages are gone, as well as the SUCCESS: <some_file> Everything Looks Good! message.


    Now, let's see the reformatting result when I run with argument --resolve-all-configs and without --check-only option:

    import os
    
    import module2
    import numpy
    
    import packageB
    

    To me this is quite unexpected, packageB went from THIRDPARTY to FIRSTPARTY and module2 went from FIRSTPARTY to THIRDPARTY.


    Second Question: (related to known_first_party inconsistencies!) Why is the sorting result different when using or not the the --resolve-all-configs argument, if the config .cfg file used is the same? If the same packageA/setup.cfg is used, I would expect the same sorting result.


    Furthermore, I noticed using --resolve-all-configs argument makes isort much slower, taking a couple seconds for such a simple repo. However, I also noticed that adding more folders/packages makes isort even slower, even if the request is exactly the same (sorting module1/2/3 only in package A and B). For example, if I added 20 more packages (packageC, packageD, ..., packageZ), with plenty of folders inside each one, the isort run with the --resolve-all-configs argument took almost 20 seconds, even if only 3 modules in 2 packages are being reformatted.


    Third Question: Why does isort with --resolve-all-configs argument become slower when adding more folders/packages, even if it is still sorting the same number of files? Shouldn't the search for the closest config file happen only for the files that are requested to sort, thus making isort run time only dependent on the number of files to check/reformat instead of the repo size?


    Finally, I went back to testing the isort standard behavior when using only a single config file (without the --resolve-all-configs argument). I changed the packageA/setup.cfg file by removing the known_first_party entry, thus making it empty, which I expect to make it resort to default configuration:

    [isort]
    
    

    If I run isort again with: python -m isort --verbose packageA/module1.py packageA/module2.py packageB/module3.py I get the following output:

    
                     _                 _
                    (_) ___  ___  _ __| |_
                    | |/ _/ / _ \/ '__  _/
                    | |\__ \/\_\/| |  | |_
                    |_|\___/\___/\_/   \_/
    
          isort your imports, so you don't have to.
    
                        VERSION 5.11.2
    
    else-type place_module for module2 returned THIRDPARTY
    else-type place_module for packageB returned FIRSTPARTY
    else-type place_module for numpy returned THIRDPARTY
    else-type place_module for os returned STDLIB
    Fixing /directory_root/packageA/module1.py
    

    which reformats the original file in this way:

    import os
    
    import module2
    import numpy
    
    import packageB
    

    Again, compared to the original configuration, packageB went from THIRDPARTY to FIRSTPARTY and module2 went from FIRSTPARTY to THIRDPARTY.


    Fourth (and Final) Question: (related to known_first_party inconsistencies!) Why do both packageB and module2 change sections if I have a default configuration vs known_first_party = bla, where bla was not even a package existing in my repo?


    For module1 formatting, I expected always to have module2 as FIRSTPARTY because it's part of the same python package and lives in the same directory, and packageB as THIRDPARTY because it's a separate package from packageA where module1 lives. And why setting known_first_party to some specific name would have an impact? Does it replace the default FIRST_PARTY, or extend?

    Additionally and probably the most important question in this issue, why does --resolve-all-configs argument change the sorting result if exactly the same config file is applied?

    opened by tiagoraulp 0
  • `--sort-reexports` is broken

    `--sort-reexports` is broken

    I decided to put two bugs in the same issue because I think sort-reexports is highly unstable and both bugs should be dealt with together.

    Bug 1

    __all__ = ('foo', 'bar')
    

    Running isort --sort-reexports on this code creates a new __all__ instead of replacing the existing one.

    __all__ = ('foo', 'bar')
    __all__ = ('bar', 'foo')
    

    Bug 2

    If you make __all__ a tuple without parentheses, then isort will just crash.

    __all__ = 'bar', 'foo'
    
    ERROR: Unrecoverable exception thrown when parsing main.py! This should NEVER happen.
    If encountered, please open an issue: https://github.com/PyCQA/isort/issues/new
    Traceback (most recent call last):
      File "/home/user/.local/bin/isort", line 8, in <module>
        sys.exit(main())
      File "/home/user/.local/lib/python3.10/site-packages/isort/main.py", line 1225, in main
        for sort_attempt in attempt_iterator:
      File "/home/user/.local/lib/python3.10/site-packages/isort/main.py", line 1209, in <genexpr>
        sort_imports(  # type: ignore
      File "/home/user/.local/lib/python3.10/site-packages/isort/main.py", line 93, in sort_imports
        incorrectly_sorted = not api.sort_file(
      File "/home/user/.local/lib/python3.10/site-packages/isort/api.py", line 429, in sort_file
        changed = sort_stream(
      File "/home/user/.local/lib/python3.10/site-packages/isort/api.py", line 210, in sort_stream
        changed = core.process(
      File "/home/user/.local/lib/python3.10/site-packages/isort/core.py", line 236, in process
        code_sorting = LITERAL_TYPE_MAPPING[stripped_line.split(" = ")[1][0]]
    KeyError: "'"
    

    Technical info

    OS: Arch Linux Python 3.10.8 isort 5.11.1

    bug 
    opened by monosans 3
Releases(5.11.4)
  • 5.11.4(Dec 21, 2022)

    Changes

    • Remove obsolete toml import from the test suite (#1978) @mgorny
    • Stop installing documentation files to top-level site-packages (#2057) @mgorny
    • Only run release workflows for upstream (#2052) @hugovk

    :package: Dependencies

    • Bump Poetry 1.3.1 (#2058) @staticdev
    Source code(tar.gz)
    Source code(zip)
  • v5.11.3(Dec 17, 2022)

    Changes

    • Renable portray (#2043) @timothycrosley
    • chore(ci): add minimum GitHub token permissions for workflows (#1969) @varunsh-coder

    :beetle: Fixes

    • Fix packaging pypoetry (#2042) @staticdev
    • Fix settings for py3.11 (#2040) @staticdev

    :construction_worker: Continuous Integration

    • General CI improvements (#2041) @staticdev
    • Add release workflow (#2026) @staticdev
    Source code(tar.gz)
    Source code(zip)
  • 5.11.3(Dec 17, 2022)

    Changes

    • Renable portray (#2043) @timothycrosley
    • chore(ci): add minimum GitHub token permissions for workflows (#1969) @varunsh-coder

    :beetle: Fixes

    • Fix packaging pypoetry (#2042) @staticdev
    • Fix settings for py3.11 (#2040) @staticdev

    :construction_worker: Continuous Integration

    • General CI improvements (#2041) @staticdev
    • Add release workflow (#2026) @staticdev
    Source code(tar.gz)
    Source code(zip)
  • 5.11.2(Dec 13, 2022)

  • 5.11.1(Dec 12, 2022)

  • 5.11.0(Dec 12, 2022)

    Changes December 12 2022

    • Add support to Python 3.11 support (#2024) @staticdev
    • Remove support to Python 3.6 (#2020) @barrelful
    • Remove restriction to Python <4.0 (#1878) @staticdev
    • Remove language_version for pre-commit hook (#1987) @rafrafek
    • Add GH release helpers (#2023) @staticdev
    • Fix integration tests (#2022) @staticdev
    • Fix unit tests (#2021) @staticdev
    • Fix Rich compatibility (#1961) @ofek
    • Fix Pyodide CDN URL (#1991) @andersk
    • Clarify description of use_parentheses (#1941) @mgedmin
    • Fix black compatibility for .pyi type stub files (#2017) @XuehaiPan
    • Add magic trailing comma option (#1876) @legau
    • Add missing space in unrecoverable exception message (#1933) @andersk
    • skip-gitignore: use allow list, not deny list (#1900) @bmalehorn
    • Infinite loop for unmatched parenthesis (#1919) @anirudnits
    • Document shared profiles (#1896) @matthewhughes934
    • Fix build-backend values in the example plugins (#1892) @mgorny
    • Remove reference to jamescurtin/isort-action (#1885) @AndrewLane
    • Split long cython import lines (#1931) @davidcollins001
    • Update plone profile: copy of black, plus three settings. (#1926) @mauritsvanrees
    • Add a command-line flag to sort all re-exports (#1862) (#1863) @parafoxia
    • Fix lines_before_imports appending lines after comments (#1861) @legau
    • Remove redundant multi_line_output = 3 from "Compatibility with black" (#1858) @jdufresne
    • Add tox config example (#1856) @umonaca
    • doc: Add examples for frozenset and tuple settings (#1822) @sgaist
    • Add multiple config documentation (#1850) @anirudnits

    :construction_worker: Continuous Integration

    • Pin versions on workflows (#2025) @staticdev

    :package: Dependencies

    • Bump certifi from 2021.10.8 to 2022.12.7 (#2018) @dependabot
    • Bump ipython from 7.16.2 to 7.16.3 (#1886) @dependabot
    Source code(tar.gz)
    Source code(zip)
  • 5.10.1(Nov 9, 2021)

    5.10.1 November 8 2021

    • Fixed #1819: Occasional inconsistency with multiple src paths.
    • Fixed #1840: skip_file ignored when on the first docstring line
    Source code(tar.gz)
    Source code(zip)
  • 5.10.0(Nov 3, 2021)

    Implemented #1796: Switch to tomli for pyproject.toml configuration loader.
    Fixed #1801: CLI bug (--exend-skip-glob, overrides instead of extending).
    Fixed #1802: respect PATH customization in nested calls to git.
    Fixed #1838: Append only with certain code snippets incorrectly adds imports.
    Added official support for Python 3.10
    
    Source code(tar.gz)
    Source code(zip)
  • 5.9.3(Jul 29, 2021)

    5.9.3 July 28 2021

    • Improved text of skipped file message to mention gitignore feature.
    • Made all exceptions pickleable.
    • Fixed #1779: Pylama integration ignores pylama specific isort config overrides.
    • Fixed #1781: --from-first CLI flag shouldn't take any arguments.
    • Fixed #1792: Sorting literals sometimes ignored when placed on first few lines of file.
    • Fixed #1777: extend_skip is not honored wit a git submodule when skip_gitignore=true.
    Source code(tar.gz)
    Source code(zip)
  • 5.9.2(Jul 8, 2021)

    5.9.2 July 8th 2021

    • Improved behavior of isort --check --atomic against Cython files.
    • Fixed #1769: Future imports added below assignments when no other imports present.
    • Fixed #1772: skip-gitignore will check files not in the git repository.
    • Fixed #1762: in some cases when skip-gitignore is set, isort fails to skip any files.
    • Fixed #1767: Encoding issues surfacing when invalid characters set in __init__.py files during placement.
    • Fixed #1771: Improved handling of skips against named streamed in content.
    Source code(tar.gz)
    Source code(zip)
  • 5.9.1(Jun 21, 2021)

  • 5.9.0(Jun 21, 2021)

    5.9.0 June 21st 2021

    • Improved CLI startup time.
    • Implemented #1697: Provisional support for PEP 582: skip __pypackages__ directories by default.
    • Implemented #1705: More intuitive handling of isort:skip_file comments on streams.
    • Implemented #1737: Support for using action comments to avoid adding imports to individual files.
    • Implemented #1750: Ability to customize output format lines.
    • Implemented #1732: Support for custom sort functions.
    • Implemented #1722: Improved behavior for running isort in atomic mode over Cython source files.
    • Fixed (https://github.com/PyCQA/isort/pull/1695): added imports being added to doc string in some cases.
    • Fixed (https://github.com/PyCQA/isort/pull/1714): in rare cases line continuation combined with tabs can output invalid code.
    • Fixed (https://github.com/PyCQA/isort/pull/1726): isort ignores reverse_sort when force_sort_within_sections is true.
    • Fixed #1741: comments in hanging indent modes can lead to invalid code.
    • Fixed #1744: repeat noqa comments dropped when * import and non * imports exist from the same package.
    • Fixed #1721: repeat noqa comments on separate from lines with force-single-line set, sometimes get dropped.
    Source code(tar.gz)
    Source code(zip)
  • 5.8.0(Mar 21, 2021)

    5.8.0 March 20th 2021

    • Fixed #1631: as import comments can in some cases be duplicated.
    • Fixed #1667: extra newline added with float-to-top, after skip, in some cases.
    • Fixed #1594: incorrect placement of noqa comments with multiple from imports.
    • Fixed #1566: in some cases different length limits for dos based line endings.
    • Implemented #1648: Export MyPY type hints.
    • Implemented #1641: Identified import statements now return runnable code.
    • Implemented #1661: Added "wemake" profile.
    • Implemented #1669: Parallel (-j) now defaults to number of CPU cores if no value is provided.
    • Implemented #1668: Added a safeguard against accidental usage against /.
    • Implemented #1638 / #1644: Provide a flag --overwrite-in-place to ensure same file handle is used after sorting.
    • Implemented #1684: Added support for extending skips with --extend-skip and --extend-skip-glob.
    • Implemented #1688: Auto identification and skipping of some invalid import statements.
    • Implemented #1645: Ability to reverse the import sorting order.
    • Implemented #1504: Added ability to push star imports to the top to avoid overriding explicitly defined imports.
    • Documented #1685: Skip doesn't support plain directory names, but skip_glob does.
    Source code(tar.gz)
    Source code(zip)
  • 5.7.0(Dec 31, 2020)

    5.7.0 December 30th 2020

    • Fixed #1612: In rare circumstances an extra comma is added after import and before comment.
    • Fixed #1593: isort encounters bug in Python 3.6.0.
    • Implemented #1596: Provide ways for extension formatting and file paths to be specified when using streaming input from CLI.
    • Implemented #1583: Ability to output and diff within a single API call to isort.file.
    • Implemented #1562, #1592 & #1593: Better more useful fatal error messages.
    • Implemented #1575: Support for automatically fixing mixed indentation of import sections.
    • Implemented #1582: Added a CLI option for skipping symlinks.
    • Implemented #1603: Support for disabling float_to_top from the command line.
    • Implemented #1604: Allow toggling section comments on and off for indented import sections.
    Source code(tar.gz)
    Source code(zip)
  • 5.6.4(Oct 13, 2020)

  • 5.6.3(Oct 11, 2020)

  • 5.6.2(Oct 10, 2020)

    5.6.2 October 10, 2020

    • Fixed #1548: On rare occasions an unecessary empty line can be added when an import is marked as skipped.
    • Fixed #1542: Bug in VERTICAL_PREFIX_FROM_MODULE_IMPORT wrap mode.
    • Fixed #1552: Pylama test dependent on source layout.
    Source code(tar.gz)
    Source code(zip)
  • 5.6.1(Oct 8, 2020)

  • 5.6.0(Oct 8, 2020)

    5.6.0 October 7, 2020

    • Implemented #1433: Provide helpful feedback in case a custom config file is specified without a configuration.
    • Implemented #1494: Default to sorting imports within .pxd files.
    • Implemented #1502: Improved float-to-top behavior when there is an existing import section present at top-of-file.
    • Implemented #1511: Support for easily seeing all files isort will be ran against using isort . --show-files.
    • Implemented #1487: Improved handling of encoding errors.
    • Improved handling of unsupported configuration option errors (see #1475).
    • Fixed #1463: Better interactive documentation for future option.
    • Fixed #1461: Quiet config option not respected by file API in some circumstances.
    • Fixed #1482: pylama integration is not working correctly out-of-the-box.
    • Fixed #1492: --check does not work with stdin source.
    • Fixed #1499: isort gets confused by single line, multi-line style comments when using float-to-top.
    • Fixed #1525: Some warnings can't be disabled with --quiet.
    • Fixed #1523: in rare cases isort can ignore direct from import if as import is also on same line.

    Potentially breaking changes:

    • Implemented #1540: Officially support Python 3.9 stdlib imports by default.
    • Fixed #1443: Incorrect third vs first party categorization - namespace packages.
    • Fixed #1486: "Google" profile is not quite Google style.
    • Fixed "PyCharm" profile to always add 2 lines to be consistent with what PyCharm "Optimize Imports" does.

    Goal Zero: (Tickets related to aspirational goal of achieving 0 regressions for remaining 5.0.0 lifespan):

    • Implemented #1472: Full testing of stdin CLI Options
    • Added additional branch coverage.
    • More projects added to integration test suite.
    Source code(tar.gz)
    Source code(zip)
  • 5.5.5(Oct 8, 2020)

  • 5.5.4(Sep 30, 2020)

    5.5.4 [Hotfix] September 29, 2020

    • Fixed #1507: in rare cases isort changes the content of multiline strings after a yield statement.
    • Fixed #1505: Support case where known_SECTION points to a section not listed in sections.
    Source code(tar.gz)
    Source code(zip)
  • 5.5.3(Sep 20, 2020)

  • 5.5.2(Sep 10, 2020)

  • 5.5.1(Sep 4, 2020)

    5.5.1 September 4, 2020

    • Fixed #1454: Ensure indented import sections with import heading and a preceding comment don't cause import sorting loops.
    • Fixed #1453: isort error when float to top on almost empty file.
    • Fixed #1456 and #1415: noqa comment moved to where flake8 cant see it.
    • Fixed #1460: .svn missing from default ignore list.
    Source code(tar.gz)
    Source code(zip)
  • 5.5.0(Sep 3, 2020)

    5.5.0 September 3, 2020

    • Fixed #1398: isort: off comment doesn't work, if it's the top comment in the file.
    • Fixed #1395: reverse_relative setting doesn't have any effect when combined with force_sort_within_sections.
    • Fixed #1399: --skip can error in the case of projects that contain recursive symlinks.
    • Fixed #1389: ensure_newline_before_comments doesn't work if comment is at top of section and sections don't have lines between them.
    • Fixed #1396: comments in imports with ";" can keep isort from recognizing import line.
    • Fixed #1380: As imports removed when combine_star is set.
    • Fixed #1382: --float-to-top has no effect if no import is already at the top.
    • Fixed #1420: isort never settles on module docstring + add import.
    • Fixed #1421: Error raised when repo contains circular symlinks.
    • Fixed #1427: noqa comment is moved from star import to constant import.
    • Fixed #1444 & 1445: Incorrect placement of import additions.
    • Fixed #1447: isort5 throws error when stdin used on Windows with deprecated args.
    • Implemented #1397: Added support for specifying config file when using git hook (thanks @diseraluca!).
    • Implemented #1405: Added support for coloring diff output.
    • Implemented #1434: New multi-line grid mode without parentheses.

    Goal Zero (Tickets related to aspirational goal of achieving 0 regressions for remaining 5.0.0 lifespan):

    • Implemented #1392: Extensive profile testing.
    • Implemented #1393: Proprety based testing applied to code snippets.
    • Implemented #1391: Create automated integration test that includes full code base of largest OpenSource isort users.

    Potentially breaking changes:

    • Fixed #1429: --check doesn't print to stderr as the documentation says. This means if you were looking for ERROR: messages for files that contain incorrect imports within stdout you will now need to look in stderr.
    Source code(tar.gz)
    Source code(zip)
  • 5.4.2(Aug 15, 2020)

    5.4.2 Aug 14, 2020

    • Fixed #1383: Known other does not work anymore with .editorconfig.
    • Fixed: Regression in first known party path expansion.
    Source code(tar.gz)
    Source code(zip)
  • 5.4.1(Aug 13, 2020)

  • 5.4.0(Aug 13, 2020)

    5.4.0 Aug 12, 2020

    • Implemented #1373: support for length sort only of direct (AKA straight) imports.
    • Fixed #1321: --combine-as loses # noqa.
    • Fixed #1375: --dont-order-by-type CLI broken.
    Source code(tar.gz)
    Source code(zip)
  • 5.3.2(Aug 7, 2020)

  • 5.3.1(Aug 7, 2020)

    5.3.1 Aug 7, 2020

    • Improve upgrade warnings to be less noisy and point to error codes for easy interoperability with Visual Studio Code (see: #1363).
    Source code(tar.gz)
    Source code(zip)
Owner
Python Code Quality Authority
Organization for code quality tools (and plugins) for the Python programming language
Python Code Quality Authority
Hide new MacBook Pro notch with black wallpaper.

Hide new MacBook Pro notch with black wallpaper.

Wang Chao 1 Oct 27, 2021
Produce a simulate-able SDF of an arbitrary mesh with convex decomposition.

Mesh-to-SDF converter Given a (potentially nasty, nonconvex) mesh, automatically creates an SDF file that describes that object. The visual geometry i

Greg Izatt 22 Nov 23, 2022
This utility synchronises spelling dictionaries from various tools with each other.

This utility synchronises spelling dictionaries from various tools with each other. This way the words that have been trained on MS Office are also correctly checked in vim or Firefox. And vice versa

Patrice Neff 2 Feb 11, 2022
one_click_kag_server is a program which tries to fully automate the creation of a King Arthur's Gold server.

one_click_kag_server is a program which tries to fully automate the creation of a King Arthur's Gold server.

Benjamin Gorman 4 Jan 05, 2022
Implementing C++ Semantics in Python

Implementing C++ Semantics in Python

Tamir Bahar 7 May 18, 2022
This is discord nitro code generator and checker made with python. This will generate nitro codes and checks if the code is valid or not. If code is valid then it will print the code leaving 2 lines and if not then it will print '*'.

Discord Nitro Generator And Checker ⚙️ Rᴜɴ Oɴ Rᴇᴘʟɪᴛ 🛠️ Lᴀɴɢᴜᴀɢᴇs Aɴᴅ Tᴏᴏʟs If you are taking code from this repository without a fork, then atleast

Vɪɴᴀʏᴀᴋ Pᴀɴᴅᴇʏ 37 Jan 07, 2023
A simple tool to move and rename Nvidia Share recordings to a more sensible format.

A simple tool to move and rename Nvidia Share recordings to a more sensible format.

Jasper Rebane 8 Dec 23, 2022
Protect your eyes from eye strain using this simple and beautiful, yet extensible break reminder

Protect your eyes from eye strain using this simple and beautiful, yet extensible break reminder

Gobinath 1.2k Jan 01, 2023
Entropy-controlled contexts in Python

Python module ordered ordered module is the opposite to random - it maintains order in the program. import random x = 5 def increase(): global x

HyperC 36 Nov 03, 2022
A morse code encoder and decoder utility.

morsedecode A morse code encoder and decoder utility. Installation Install it via pip: pip install morsedecode Alternatively, you can use pipx to run

Tushar Sadhwani 2 Dec 25, 2021
Simple integer-valued time series bit packing

Smahat allows to encode a sequence of integer values using a fixed (for all values) number of bits but minimal with regards to the data range. For example: for a series of boolean values only one bit

Ghiles Meddour 7 Aug 27, 2021
Know your customer pipeline in apache air flow

KYC_pipline Know your customer pipeline in apache air flow For a successful pipeline run take these steps: Run you Airflow server Admin - connection

saeed 4 Aug 01, 2022
NFT-Generator is the best way to generate thousands of NFTs quick and easily with Python.

NFT-Generator is the best way to generate thousands of NFTs quick and easily with Python. Just add your files, set your configuration and run the scri

78 Dec 27, 2022
A dictionary that can be flattened and re-inflated

deflatable-dict A dictionary that can be flattened and re-inflated. Particularly useful if you're interacting with yaml, for example. Installation wit

Lucas Sargent 2 Oct 18, 2021
Extends the pyranges module with operations on joined genomic intervals

tiedpyranges Extends the pyranges module with operations on joined genomic intervals (e.g. exons of same transcript) Install with: pip install tiedpyr

Marco Mariotti 4 Aug 05, 2022
Edit SRT files to delay subtitle time-stamps.

subtitle-delay A program written in Python that directly edits SRT file to delay the subtitles. Features: Will throw an error if delaying with negativ

8 Jul 17, 2022
Nmap script to guess* a GitLab version.

gitlab-version-nse Nmap script to guess* a GitLab version. Usage https://github.com/righel/gitlab-version-nse cd gitlab-version-nse nmap target --s

Luciano Righetti 120 Dec 05, 2022
Python script to launch burp scans automatically

SimpleAutoBurp Python script that takes a config.json file as config and uses Burp Suite Pro to scan a list of websites.

Adan Álvarez 26 Jul 18, 2022
Playing with python imports and inducing those pesky errors.

super-duper-python-imports In this repository we are playing with python imports and inducing those pesky ImportErrors. File Organization project │

James Kelsey 2 Oct 14, 2021
Script to decrypt / import chromium (edge/chrome) cookies

Cloonie Script to decrypt / import chromium (edge/chrome) cookies. Requirements Install the python dependencies via pip: pip install -r requirements.t

Lorenzo Bernardi 5 Sep 13, 2022