I am switching over to using Black for all my Python projects from now on. Till now I had been using autopep8 as my auto-formatter and isort to sort my imports. But while using Black I found out that Black alone does the job of isort too alongside formatting my code. While I do not mind the way Black sorts my imports, I would still like to use isort to handle my imports and I would like Black to handle only my code, not the imports. So, is there any way to configure Black to only format my code and not touch the imports? I am using VS Code by the way so some help on how to apply the configuration in VS Code will help too. Thanks!
Asked
Active
Viewed 4,978 times
7
-
Can you get black to run first, followed by isort? – quamrana May 21 '21 at 13:32
-
Unfortunately black can not do what isort does, black is only a formatter (not a linter) so running black can not change the AST. Changing the order of imports will change the AST and therefore is not acceptable by black. To achieve what you want you should firstly use `isort` (and `autoflake -r --in-place --remove-unused-variables` if you need to remove unused imports) and then format with `black` – Matteo Zanoni May 21 '21 at 13:36
-
I am not sure if VS Code can be configured to run black first and then isort automatically when I format my document. – Arafat Khan May 21 '21 at 13:38
-
You should actually run isort first... – Matteo Zanoni May 21 '21 at 13:41
1 Answers
7
Add those to jobs setting in vscode, it should do the trick
{
"python.formatting.provider": "black",
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}

Matteo Zanoni
- 3,429
- 9
- 27