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

132.1k views Asked by At

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..

21

There are 21 answers

8
neves On BEST ANSWER

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

0
Antoine On

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
0
camab On

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.

3
Mark On

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
  }
1
wisbucky On

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.
0
hi2meuk On

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.

2
maxprehl On

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!

7
abnerl On

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.

1
Md. Sahaib Mridha On

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.

0
Brad On

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.

1
Furkan On

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.

1
Super Kai - Kazuya Ito On

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
    }
}
1
Stephen Herr On

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

1
CentAu On

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

1
yemy On

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 }
0
mobeen ali On

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

0
nocibambi On

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.

0
brocla On

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.

0
John Targaryen On

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

0
Matt Najarian On

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

0
Joep On

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