Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvacek/efe6b6fec1bbeb25718bc89b9c1b5acc to your computer and use it in GitHub Desktop.
Save jvacek/efe6b6fec1bbeb25718bc89b9c1b5acc to your computer and use it in GitHub Desktop.
Remove unused python imports on save in VSCode

Auto-remove unused python imports in VSCode on save

I could not find a proper full configuration for this online, and I know I'll need this again in the future.

There are two ways to achieve this with some plugins; one via hitting the shell and doing an in-place replace, the other is by doing it with extensions configurable in vscode. Both should give you the same results.

Install VSCode extensions needed:

If running via bash:

If running via extensions only:

Install autoflake

You will need this whichever way you run this

# Install the package into your system or your virtualenv
pip3 install autoflake
# Copy the path from below
which autoflake

Paste this in your settings

For shell-based one

//Remove Unused Python imports via bash
"emeraldwalk.runonsave": {
    "commands": [
        {
            "match": "\\.py$",
            "isAsync": true,
            // Use the full path from above in case it can't find it
            "cmd": "autoflake --in-place --remove-all-unused-imports \"${file}\""
        },
    ]
},

For the extension-based one

// Autoflake settings are also available in the UI-based settings.
// Check that the Autoflake extension runs first. If not, might need to change the path.
"autoflake.path": "/path/to/your/autoflake"
// Make it remove *all* imports, not just the standard ones
"autoflake.removeAllUnusedImports": true

//Remove Unused Python imports via bash
"runItOn": {
    "commands": [
        {
            "match": "\\.py$",
            "isShellCommand": false,
            "isAsync": true,
            "cmd": "autoflake.removeUnused"
        },
    ]
},
@spookyuser
Copy link

Thanks!

You can also do this now

  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.organizeImports": true,
    "source.fixAll": true
  },

@simplast
Copy link

simplast commented Jun 7, 2023

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment