visual-studio-coderuff

Using Ruff with VSCode, how to prevent automatic removal of unused imports


I'm using VSCode with the Ruff extension for linting and autoformat. I know the cost of unused imports but sometimes I just need to comment a line for a test and it's really bothering to see the associated import being wiped out automatically.

The optimal behaviour for me would be to comment out the imports instead of brutally removing them !

I found this question : How to stop VS Code from removing Python unused imports on save

But it does not help, I suspect because Ruff is overwriting the source behaviour. I see here : https://docs.astral.sh/ruff/settings/#lint_ignore that I should be able to ignore rule F401 but I can't find how to do this in VSCode.

Here's how my settings.json looks (see how I tried to jam source.organizeImports and source.sortImports...) :

{
    "[python]": {
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": "never",
            "source.sortImports": "explicit",
            "source.fixAll": "explicit",
        },
        "editor.defaultFormatter": "charliermarsh.ruff",
    },
}

What I'm trying to achieve does not look very complicated but any help would be well appreciated :)


Solution

  • There's an example given by Charlie Marsh here. He instructs to put the following in your pyproject.toml, ruff.toml, or .ruff.toml file (if you don't have one, create one):

    [lint]
    # Disable fix for unused imports (`F401`).
    unfixable = ["F401"]
    

    There's also the option to use "ruff.lint.ignore": ["F401"] in settings.json instead. The setting is contributed by the Ruff extension for VS Code.*

    Or you could try this (see docs), but this and the ruff.lint.ignore settings would only apply when using VS Code with the Ruff extension:

    "ruff.configuration": {
        "lint": {
            "unfixable": ["F401"],
        },
    },
    

    I suggest you also read https://github.com/astral-sh/ruff-vscode?tab=readme-ov-file#configuring-ruff.

    There's also a special case lint setting for init modules only: ignore-init-module-imports.


    * Other related settings include ruff.lint.args, and ruff.format.args.