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

1

6

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 :)

Foxe answered 4/4 at 8:38 Comment(1)
@nitwit maybe you should explain why you think this is a duplicate instead. I for one can't see how.Chivalry
C
5

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 the ruff.lint.args VS Code setting contributed by the ruff extension.

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.

Chivalry answered 4/4 at 23:25 Comment(1)
Thanks, I was missing the "ruff.lint.args" keyword. I will consider adding a ruff.toml but it seems overkill for what I'm doing right now :)Foxe

© 2022 - 2024 — McMap. All rights reserved.