Formatter black is not working on my VSCode...but why?
Asked Answered
T

22

72

I have started using Python and Django and I am very new in this field. And, this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue...

When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. & Mine did not show up that message.

So what I did was...

  1. manually input 'pipenv install flack --dev --pre' on terminal.

  2. manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder.

  3. Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8

The bottom code is from settings.json (on vscode folder).

{
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.formatting.provider": "black", # input manually
  "python.linting.flake8Args": ["--max-line-length=88"] # input manually
}

I found a 'black formatter' document. https://github.com/psf/black & it stated... python -m black {source_file_or_directory} & I get the following error message.


    Usage: __main__.py [OPTIONS] [SRC]...
Try '__main__.py -h' for help.

Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist.

Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on the right track or not.

Can I hear your advice? At least some direction to go, please. Thanks..

Thermocline answered 2/12, 2020 at 2:39 Comment(2)
Wow...I guess now I partly see how each post is going on here. Thank you for all your help everyone! Stay safe!Thermocline
This fixed - #57751380Shiff
R
113

Update 2023-09-15:

Now VSCode has a Microsoft oficial Black Formatter extension. It will probably solve your problems.

Original answer:

I use Black from inside VSCode and it rocks. It frees mental cycles that you would spend deciding how to format your code. It's best to use it from your favorite editor. Just run from the command line if you need to format a lot of files at once.

First, check if you have this in your VSCode settings.json (open it with Ctrl-P + settings):

"python.formatting.provider": "black",
"editor.formatOnSave": true,

Remember that there may be 2 setting.json files: one in your home dir, and one in your project (.vscode/settings.json). The one inside the project prevails.

That said, these kind of problems usually are about using a python interpreter where black isn't installed. I recommend the use of virtual environments, but first check your python interpreter on the status bar:

Python interpreter in the status bar of VSCode

If you didn't explicitly select an interpreter, do it now clicking on the Python version in your status bar. You can also do it with Ctrl-P + "Python: Select Interpreter". The status bar should change after selecting it.

Now open a new terminal. Since you selected your interpreter, your virtual environment should be automatically activated by VSCode. Run python using your interpreter path and try to import black:

$ python
Python 3.7.3 (default, Mar 27 2019, 22:11:17) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import black
>>> 

Failed import? Problem solved. Just install black using the interpreter from the venv: python -m pip install black. You also can install using Conda, but in my experience VSCode works better with pip.

Still not working? Click in the "OUTPUT" tab sibling of the TERMINAL and try to get more info at the "Log" output (if you use the newer Black plugun it may be called "Black Formatter"). Select it in the pull down menu:

log output of vscode

Retharethink answered 25/2, 2021 at 11:55 Comment(8)
Sorry for late reply. You even showed me a better option! Thank you so much and stay safe!Thermocline
Also potentially worth noting: with black installed and configured, I found that I must save the file to disk - you can't just copy/paste a snippet of code into VSCode and format it (not entirely surprising although it would be nice if VSCode could manage that by creating a temp file to hand to black or something as I love VSCode's compare for things like looking at two complex dictionaries side-by-side)Sadler
For me, it was useful to check the OUTPUT "Python" log. The "Log (Main)" did not contain any information when invoking "Format Document".Truelove
If you go over all the above processes and still got blocked. You can upgrade your black package to latest verion. It works for me after upgrade to 22.3.0.Ulcerate
I was experiencing the same problem. I had installed Black via Conda, and the latest available version was 19.10b0=py_0. My Conda environment was active, but Black did not do anything in VS Code. So I uninstalled Black via Conda, and re-installed it via PyPI (pip) within my Conda environment. The latest version of Black available via PyPI was 22.3.0. Now, Black works correctly in VS Code.Animalcule
This option doesn't exist anymoreCalcicole
This answer is no longer correct as of 2023-09-01 on VS Code Aug 2023 and possibly July 2023. You now need to install a separate extension (Black Formatter, by Microsoft). See marketplace.visualstudio.com/…Incurvate
Looking for the logs in output helped me. I looked to the "black formatter" logs, as I already have the new MS extension. My problem was with my configs, I had set the --line-length in the wrong section of settings.json!Cobelligerent
Q
60

2024/02/19 updated

The previous solution doesn't work anymore.

There're two issues:

  1. vscode has new official extension
  2. different black output from vscode extension and black in your python virtual environment

If you just want to use 'black' formatter and don't care issue #2. Just install vscode black extension

enter image description here

I revised my solution for issue #2
a. install black extension first
b. set up your virtual environment, install black init and set your project interpreter to it
c. go to user setting, set Black-formatter: Path to "black" in your virtual environment

"black-formatter.path": ["black"]

NOTE: Install 'black' in the python environment you need, remove global 'black'

===== Obselete solution for old vscode =====
Attach my finding for those who still can't solve the Black formatting issue in VS Code.

First, you have to install Black globally or locally (if you use virtual env like conda).

Then, make sure your VS settings as following, set python default formatter provider as 'black':

enter image description here

Finally, open settings.json of your VS Code, add the following segment for it.

"[python]": {
    "editor.defaultFormatter": null,
    "editor.insertSpaces": true,
    "editor.tabSize": 4,
    "editor.formatOnSave": true
}

The key point is:

"editor.defaultFormatter": null

If you still use "editor.defaultFormatter": "black" as many old posts suggest, the Black formatter will not work in newer VS Code.

Quadrinomial answered 19/10, 2021 at 7:44 Comment(8)
Thanks! This fixed it for me: "editor.defaultFormatter": nullPhenazine
This also worked for me, anything else did notSabir
yeah, this worked for me as well! This issue was driving me insane!Isobaric
such a weird bugHereditament
This did not work for me. The editor complained of no formatter being set and made me choose the ms one again. However, I removed the line completely and that finally got the formatter to work.Kavanagh
This answer is no longer sufficient as of 2023-09-01 on VS Code Aug 2023 and possibly July 2023. You now need to install a separate extension marketplace.visualstudio.com/…Incurvate
For me, it the issue was that I had "editor.defaultFormatter": "esbenp.prettier-vscode" in my settings.json, which of course didn't work for Python files. I switched to the below and that allowed black to run for .py files. "[typescript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }Wunder
The updated suggestion worked as of 4/19/2024Brutality
R
13

For those who have tried it all :).

Black will not work in VSCode if you have

  • a syntax error,
  • an IPython magic (e.g., %matplotlib inline).

Running black from the terminal on the file reveals these issues.

Randall answered 21/10, 2021 at 9:16 Comment(0)
S
10

There is a new extension, currently pre-release, for formatting with black. See v1.67 Release Notes, Python Black formatting.

From the README (vscode Marketplace: Black Formatter):

Usage

Once installed in Visual Studio Code, "Black Formatter" will be available as a formatter for python files. Please select "Black Formatter" (extension id:ms-python.black-formatter) as the default formatter. You can do this either by using the context menu (right click on a open python file in the editor) and select "Format Document With...", or you can add the following to your settings:

  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter"
  }

Format on save

You can enable format on save for python by having the following values in your settings:

  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  }
Sherlene answered 2/5, 2022 at 18:37 Comment(3)
Nothing else worked for me.Beka
This worked! I hit Command-Shift-P --> Format Document and it prompted for a default formatter because this was not set. Many thanks!Foy
I think a lot of the confusion is that this plugin is still very new and all the advice online is referencing the old plugin or explaining how to use a local version of black (as opposed to the one bundled in the plugin).Renayrenckens
L
9

Like camab said, you can totally run it from the command line:

$ black file.py

You can also run it on a whole folder (directory) of python files:

ex if I have:

src/
| - module/
|   | - moduleFile.py
|   \ - __init__.py
|
\ - script.py

and run

$ black src

it would format moduleFile.py, __init__.py, and script.py.

As far as your VSCode config goes, I also like to have in settings.json

{
    "editor.formatOnSave": true,
    "python.linting.lintOnSave": true,
}

to make sure that every time I press save the file is getting linted and formatted.

If you ever have issues with linting/formatting in VSCode you can use the "Command Palette" (Ctrl+Shift+P) to force the following commands:

  • Python: Run Linting
  • Python: Select Linter
  • Format Document
  • Format Document With...

Which should produce a visual pop-up style error if there's actually a problem.

Hope this helps and happy coding!

Lossa answered 5/2, 2021 at 21:46 Comment(2)
Thank you for answering my question! Stay safe!Thermocline
This help me discover the following error: ImportError: cannot import name '_unicodefun' from 'click'Mahdi
J
9

For those who see this and none of the above solutions work. If you set the black path to its absolute location it might solve the problem.

enter image description here

Jaimiejain answered 11/2, 2022 at 0:7 Comment(1)
This worked for me after the other answers did not.Freestone
L
6

Another possibility is that you have added incorrectly formatted black arguments. The plugin wants every space-separated option to be added as a it's own "item" in the Settings UI like so: black args setting

You should be able to see the args pass through correctly into the Output->Python console like so: good black command

It should not look like this:

bad black command

Litotes answered 14/6, 2022 at 16:54 Comment(2)
Yes! This was my problem too. Thank you:) Fixing this took quite a while - these problems should be logged!Attest
This was my issue too. Wish that silent error in the output was given a pop-up!Mcgehee
T
5

You can install Black extension to VSCode as shown below. *I use Anaconda on Windows 11:

enter image description here

Then, set the code below to settings.json. *You can see my answer explaning how to open settings.json:

// "settings.json"

"[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
}

This below is my full settings.json with the code above:

// "settings.json"

{
    "python.defaultInterpreterPath": "C:\\Users\\kai\\anaconda3\\python.exe",
    "window.zoomLevel": 3,
    "files.autoSave": "afterDelay",
    "breadcrumbs.enabled": false,
    "[python]": { // Here
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true
    }
}
Topper answered 12/6, 2023 at 5:8 Comment(1)
Note that this extension uses it's own, bundled version of Black by default. To force it to use the black executable from your environment, use "black-formatter.importStrategy": "fromEnvironment".Archer
Y
4

Another possibility is that a syntax error is preventing Black from working. Black will not apply any formatting changes if there is a syntax error.

However, VS Code still displays "Formatting with Black" in the status bar and silently fails.

You can verify this by running Black from the command line, which will show the error if there is one:

$ black foo.py
error: cannot format foo.py: Cannot parse: 328:4:     :

Oh no! 💥 💔 💥
1 file failed to reformat.
Youngstown answered 29/12, 2022 at 19:41 Comment(2)
Spoke like a wise person: Thanks for the solution. I have been scratching my head trying to debug, why formatting fails sometimes. And it was randomBlennioid
This worked for me. After try this I realize that Bit Defender AV was blocking the black.exe in Sandbox. After a few minutes the AV analysis finished and the file was allowed to run... then, I could see that there was a syntax error that VS Code didn't warn about, and that was preventing Black from working. After correcting the syntax everything returned to normal.Carburet
O
3

I had that same problem and only cure was to remove

   "python.formatting.blackArgs": ["--skip-numeric-underscore-normalization"],  

from setting.json. It doesn't make sense but it works.

Obstruent answered 11/1, 2022 at 16:34 Comment(1)
Exactly my case!! I was going crazyMisdemeanant
C
3

Probably you have conflicts with your default formatter just add "[python]": { "editor.defaultFormatter": null } to your Open User Settings in VSC.

"editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "python.formatting.provider": "black",
  "[python]": { "editor.defaultFormatter": null }
Chorale answered 16/10, 2022 at 11:28 Comment(1)
Yes, having a default formatter set messes with the Python formatters. This was tripping me up despite all the other settings being correct.Urbani
A
2

For me the problem was not black directly, but an invalid project settings file that it reads to find config settings. The root cause was not logged anywhere.

I found the cause by checking the OUTPUT tab with Python extension selected. It showed black being called with apparently no problems reported:

./.venv/bin/python -m black --diff --quiet ./myfile.py
cwd: .

However when I ran the same command in the terminal I got the error reported:

Error: Could not open file './pyproject.toml': Error reading configuration file: Invalid value (at line 18, column 10)

When this was fixed I could format my code manually and format on save was back too.

Aha answered 22/3, 2022 at 19:6 Comment(0)
A
2

Yet another reason that black may stop working when run from vs code...

Perhaps you have started using Python 3.10

Black will fail if new features like Structural Pattern Matching are used. VS Code fails silently. No formatting happens. It appears that black isn't working.

Try running black from the command line to see if there are error messages.

This is what I got:

$ black my_code.py 
error: cannot format my_code.py: Cannot parse: 57:14:         match rec.split():
Consider using --target-version py310 to parse Python 3.10 code.
Oh no! 💥 💔 💥
1 file failed to reformat.

I had to add --target-version=py310 to VS Code's blackArgs, like this:

"python.formatting.blackArgs": ["--target-version=py310"]

Note the equals (=) sign.

Aloes answered 14/9, 2022 at 13:5 Comment(0)
T
2

If you are working on dev container then you might need to install Black Formatter extension. It worked for me, here is the link:

https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter

Tynishatynwald answered 2/11, 2022 at 21:47 Comment(0)
O
2

In my case I had accidentally uninstalled one of black's dependencies, mypy-extensions. Vscode did not show an error in the UI or the output logs. Try reinstalling black with pip install black --force-reinstall.

Ose answered 1/3, 2023 at 2:24 Comment(0)
N
1

If you are using windows operating system, then there is a simplest solution:

  1. Find out where you have installed black package. It can be on AppData/python/scripts
  2. Click on start menu and type "Edit the system environment variables" and select it.
  3. now click on environment variable and double click on 'path' from 'System Variable' portion to edit.
  4. now add the package path here like "Appdata/path/scripts;"

Hopefully now black will work fine on every save.

This solution works fine for me.

Note: Now you can use black from CLI.

Nugget answered 7/4, 2021 at 22:38 Comment(1)
Thank you for answering this question! Stay safe!Thermocline
A
1

Nothing in this question worked for my black. I gave up and switched default formatter in Settings > UI to autopep8 instead and everything worked.

Aquarius answered 30/9, 2022 at 19:2 Comment(0)
T
1

It was a challenging issue for me to resolve. I even reinstalled my VSCode and Black-Formatter several times. Finally I found the issue using the following method. In the VSCode click on OUTOUT and from the dropdown menu select Black-Formatter. There in the logs you will see the issue (as in screenshot below). Here for me it was that I had the following items in my .gitignore file. Disabling the last two items solved the issue for me (still doesn't make sense that it broke the black formatter)

__pycache__/
*/__pycache__/
*\__pycache__\

enter image description here

Tereasaterebene answered 14/4, 2023 at 20:55 Comment(0)
I
1

Following the answer above (check the logs in the OUTPUT), I found the following message(s):

[info] Formatting requested before server has started.

The solution was to press CTRL+SHIFT+P and execute the command

BlackFormatter: Restart Server
Inhesion answered 19/10, 2023 at 8:37 Comment(0)
C
0

My Bit Defender AV on Windows 11 is blocking the ".\venv\Scripts\black.exe" and keeping it in Sandbox... great!! :(

Thanks to @wisbucky's answer... After trying what he advised, I could see that the that Bit Defender AV was blocking the black.exe in Sandbox. After a few minutes the AV analysis finished and the black.exe file was allowed to run... then, I could see that there was a syntax error that VS Code didn't warn about, and that was preventing Black from working.

After correcting the syntax everything returned to normal.

Carburet answered 19/4, 2024 at 21:44 Comment(0)
H
-2

Check if the formatter is configured correctly by calling the 'Format Document' action (ctrl+shift+p). This prompted me with a message to choose the formatter. After that everything worked as expected.

format document

Hiers answered 17/4, 2023 at 9:48 Comment(0)
S
-3

The best way to use black is through terminal in my opinion. All you need to do is install it on pip on terminal using: pip install black Then when it's installed you go onto terminal and type: black filename.py

the full line would be: black filepath/file.py So for a file called test.py located on desktop if on mac: black desktop/test.py If you want to do it on multiple files than do it individually to each file.

Segalman answered 2/12, 2020 at 3:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.