Skip to content

Instantly share code, notes, and snippets.

@cb109
Last active October 19, 2024 04:55
Show Gist options
  • Save cb109/47496649640c9c5f4287b06db7a7c197 to your computer and use it in GitHub Desktop.
Save cb109/47496649640c9c5f4287b06db7a7c197 to your computer and use it in GitHub Desktop.
VSCode: Python Sort Imports on File Save (isort)

VSCode: Python Sort Imports on File Save (isort)

Update 2024

VSCode used to have issues with sorting Python imports (2021), as described further down below, but this has since been fixed.

All you need to do to make VSCode use its builtin isort on save is this in your settings.json:

"[python]": {
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": "explicit"
    },
},

See this Changelog about the "explicit". If you want to use a specific isort profile, do this in addition:

"isort.args": [
    "--profile", "black"
],

If you'd like to use an isort configuration file like .isort.cfg (or one of these alternatives), point it to the folder that the file is in, e.g. your workspace root:

"isort.args": [
    "--settings-path", "${workspaceFolder}"
],

Note: To detect changes in that .isort.cfg I have to restart VSCode and it takes a moment to pick up the new config afterwards.

If you are using ruff for formatting in VSCode, it also has an option to organizeImports, in case that conflicts you can turn it off:

"ruff.organizeImports": false,

The stuff below is outdated, but I will leave it there for reference!


Outdated instructions 2021-2023

Problem

VSCode does have support to sort imports inside a .py file using isort. The recommended way to turn this on is via the following settings:

"[python]": {
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": true,
    },
}

Sadly, this seems to ignore anything configured in python.sortImports.args and produces different and buggy results (e.g. duplicate imports) on subsequential runs.

Calling the Sort Imports command manually inside the UI works flawlessly, so I've tried to instead do:

"[python]": {
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "python.sortImports": true,
    },
}

However this has no effect, probably because python.sortImports is not properly identified as a valid code action to trigger (?). Maybe it's a bug.

Workaround

We can still make this work though. Using the multicommand extension we can define a "Save File" command targetting python files in which we call the "Sort Imports" beforehand.

Add the following to your settings:

"multiCommand.commands": [
  {
    "command": "multiCommand.saveFileAndSortImportsWhenPython",
    "sequence": [
      "python.sortImports",
      "workbench.action.files.save"
    ]
  }
]

And configure a new keybinding for it that will take precedence over the default save-file command when working on a Python file:

{
  "command": "multiCommand.saveFileAndSortImportsWhenPython",
  "key": "ctrl+s",
  "when": "resourceLangId == 'python'"
}

Done! Your imports are sorted properly now and will respect any additional settings :)

For compatibility with black see: https://pycqa.github.io/isort/docs/configuration/black_compatibility/

By the way, these settings seem to play nicely together with black, which is also supported natively by vscode's python extension:

"python.sortImports.args": [
    "--trailing-comma",
    "--force-grid-wrap", "0",
    "--use-parentheses",
    "--force-single-line-imports",
    "--line-width", "88",
    "--multi-line", "3",
    "--float-to-top"
],

The better way would be to reuse the exact configuration by pointing vscode to the directory that contains one of the possible config files (.isort.cfg, tox.ini, setup.cfg):

"python.sortImports.args": [
    "--settings-path", "${workspaceFolder}",
],
@TomGrobbe
Copy link

Thanks for this, I was looking to fix the terrible default behavior of organize imports, and your python.sortImports.args section really helped with that.

After experimenting with the editor.codeActionsOnSave some more, this seems to organize the imports on save without having to make a custom command:

"[python]": {
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    },

source.organizeImports is identified as a valid command, and works fine in my case. I am using Pylance as linting server. I'm not sure if that has anything to do with it but at least this works.

@GBrachetta
Copy link

Thank you for sharing this! Could you please let me know where can I find all the options available to pass inside "python.sortImports.args"?
I would love to force the formatter to arrange imports indented and vertically aligned, like so:

from some_module import (
  something,
  something_else,
  yet_some_other,
)

But I cannot find the source of this information. Thank you!

@cb109
Copy link
Author

cb109 commented Feb 7, 2021

@GBrachetta Those options are taken from theisort CLI which you can get help on via:

$ pip install isort
$ isort --help

@GBrachetta
Copy link

Thank you, that helped a lot! :)

@den-is
Copy link

den-is commented Nov 27, 2021

Hey, thanks for your trials and helpful settings.
I've encountered the very same issue.
Have you opened an issue for that "bug"? I think we should unite and request a fix.

VSCode ignores "python.sortImports": true, key, and for example on the creation of RemoteContainerEnv - completely ignores that setting key in resulting VSCode settings. (i.e. not includes, drops)

Also both blakc and isort can be configured together in a single pyproject.toml in the project's root.

Also potentially with modern isort everything should work without explicitly configuring it but just passing --profile=black to isort.

UPD
Found related issue microsoft/vscode-python#7042

@shadycuz
Copy link

I only had to do 2 things. Use the vscode settings here https://eshlox.net/2019/12/02/vscode-sort-python-imports-automatically

That made import sorting happen automatically on save. I use black for formatting so I also had to create a config file for isort to set the profile to black. Details here https://pycqa.github.io/isort/docs/configuration/black_compatibility.html

@melyux
Copy link

melyux commented Jul 5, 2024

Organize Imports isn't available as a Source Action for me in Python on VSCode, only "Remove all unused imports".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment