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}",
],
@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