How to make VSCode honor black excluded files in pyproject.toml configuration when using formatOnSave

5.4k views Asked by At

I have the following pyproject.toml for configuring black:

[tool.black]
exclude = 'foo.py'

If I run black . from the project's root folder that only contains foo.py, I get No Python files are present to be formatted. Nothing to do � as expected.

However, when I save foo.py from within VS Code (I have black configured as the formatter and enabled Format On Save), the file is still formatted by black.

Interestingly, VS Code seems to honor other configurations, e.g. line-length.

Is there a way to make VSCode honor the exclude configuration?

2

There are 2 answers

0
frankundfrei On BEST ANSWER

The --force-exclude option also excludes files if they are explicitly listed. Thus, it also works with formatOnSave in VS Code.

In the example above, simply use

[tool.black]
force-exclude = 'foo.py'
1
frankundfrei On

If you list a file explicitly, this takes precedence over the any excluded files. This seems to be what black's developers consider the expected behaviour, see for example this issue. Also, this won't be fixed within vscode, see this issue.

This is also a problem when using pre-commit.

Since I didn't want to maintain yet another list (I do this for pre-commit already) of files for which I do not want to use FormatOnSave I ended up using a different approach. Since all of the files that I don't want to auto-format on save reside in a specific folder within my project, I ended up using the workaround described in this answer and deactivate FormatOnSave in the sub-folder settings.