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

Viewed 37341

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

12 Answers

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

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, the 'black' formatter will not work in newer vs code.

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!

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.

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

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.

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.

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.

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
  }

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

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.

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.

Related