sachinruk
sachinruk

Reputation: 9869

Move isort configs to vscode settings.json

I understand that VSCode: how to config 'Organize imports' for Python (isort) may be related, but all the answers seems outdated.

I have the following in my pyproject.toml file and my settings.json is shown below. While black seems to run properly, I can't seem to run isort without manually typing in isort ..

Side question, isort seems to be slow when I run it via terminal, should I simply add a pre-commit hook instead if isort is generally slow?

[tool.black]
line_length = 100

[tool.isort]
honor_noqa = true
line_length = 100
profile = "black"
verbose = false

known_first_party = [
    # all folders you want to lump
  "src",
]

# Block below is google style import formatting https://pycqa.github.io/isort/docs/configuration/profiles.html
force_sort_within_sections = true
force_single_line = true
lexicographical = true
single_line_exclusions = ["typing"]
order_by_type = false
group_by_package = true
{
    "files.insertFinalNewline": true,
    "jupyter.debugJustMyCode": false,
    "editor.formatOnSave": true,
    "editor.formatOnPaste": true,
    "files.autoSave": "onFocusChange",
    "editor.defaultFormatter": "ms-python.black-formatter",
    "black-formatter.path": ["/opt/homebrew/bin/black"],
    "black-formatter.args": ["--config", "./pyproject.toml"],
    "black-formatter.cwd": "${workspaceFolder}",
    "isort.args": ["--config", "./pyproject.toml"],
    "isort.check": true,
    "python.analysis.typeCheckingMode": "basic",
}

Upvotes: 0

Views: 299

Answers (2)

immersinn
immersinn

Reputation: 11

In addition to "source.organizeImports": "explicit" and "isort.args":["--profile", "black"], using "isort.importStrategy": "fromEnvironment" will allow isort to use the current env to properly sort imports in files from the local / dev package being used.

From: https://marketplace.visualstudio.com/items?itemName=ms-python.isort#settings.

Full example:

{
    "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
          "source.organizeImports": "explicit"
    },
  },
  "isort.args":["--profile", "black"],
  "isort.importStrategy": "fromEnvironment"
}

Upvotes: 1

MingJie-MSFT
MingJie-MSFT

Reputation: 9209

You could add the following codes to your settings.json if you want to be able to sort automatically rather than manually type command:

  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": {
        "source.organizeImports": "explicit"
    },
  },
  "isort.args":["--profile", "black"],

Upvotes: 0

Related Questions