51

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

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
mireumireu
  • 705
  • 1
  • 7
  • 9
  • Wow...I guess now I partly see how each post is going on here. Thank you for all your help everyone! Stay safe! – mireumireu Apr 10 '21 at 08:47

20 Answers20

83

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. Select it in the pull down menu:

log output of vscode

neves
  • 33,186
  • 27
  • 159
  • 192
  • 1
    Sorry for late reply. You even showed me a better option! Thank you so much and stay safe! – mireumireu Apr 10 '21 at 08:44
  • 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) – Rick Riensche Jul 30 '21 at 17:22
  • 5
    For me, it was useful to check the OUTPUT "Python" log. The "Log (Main)" did not contain any information when invoking "Format Document". – typ1232 Nov 17 '21 at 11:45
  • 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`. – Jaden May 16 '22 at 05:56
  • 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. – leifericf Jun 10 '22 at 08:45
53

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.

Wolf
  • 9,679
  • 7
  • 62
  • 108
abnerl
  • 643
  • 5
  • 6
9

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.

nocibambi
  • 2,065
  • 1
  • 16
  • 22
8

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!

maxprehl
  • 83
  • 2
  • 8
8

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

CentAu
  • 10,660
  • 15
  • 59
  • 85
8

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
  }
Mark
  • 143,421
  • 24
  • 428
  • 436
  • Nothing else worked for me. – MattG Sep 30 '22 at 15:39
  • This worked! I hit Command-Shift-P --> Format Document and it prompted for a default formatter because this was not set. Many thanks! – SilentRhetoric Apr 22 '23 at 14:35
  • 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). – Captain Man Apr 25 '23 at 19:20
4

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

Stephen Herr
  • 91
  • 1
  • 3
  • Yes! This was my problem too. Thank you:) Fixing this took quite a while - these problems should be logged! – sunew Feb 10 '23 at 15:56
4

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
    }
}
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
  • 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"`. – Niko Föhr Jun 30 '23 at 12:58
2

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 }
Max Hager
  • 536
  • 4
  • 13
  • Yes, having a default formatter set messes with the Python formatters. This was tripping me up despite all the other settings being correct. – renderbox Jan 13 '23 at 16:46
2

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.
wisbucky
  • 33,218
  • 10
  • 150
  • 101
  • 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 random – user2359003 Mar 22 '23 at 19:16
1

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.

Furkan
  • 39
  • 5
1

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.

hi2meuk
  • 1,080
  • 11
  • 9
1

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.

brocla
  • 123
  • 6
1

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

mobeen ali
  • 85
  • 1
  • 11
1

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.

Brad
  • 121
  • 1
  • 8
0

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.

Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
0

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

John Targaryen
  • 1,109
  • 1
  • 13
  • 29
0

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

Matt Najarian
  • 151
  • 1
  • 8
-1

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

Joep
  • 788
  • 2
  • 8
  • 23
-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.

camab
  • 3
  • 3