Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save esprengle/82e0a070ccf278a10792f15099a86b5d to your computer and use it in GitHub Desktop.
Save esprengle/82e0a070ccf278a10792f15099a86b5d 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)

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}",
],
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment