Hướng dẫn black, python vscode

Hướng dẫn black, python vscode

Adam Lombard

Posted on Apr 30, 2020 • Updated on May 1, 2020

Black is "the uncompromising Python code formatter." It can be configured to automatically format your code whenever you save a file in VSCode.

Install Black in your virtual environment:

$ pip install black

Enter fullscreen mode Exit fullscreen mode

Install Microsoft's Python extension in VSCode:

Hướng dẫn black, python vscode

Open your VSCode settings, by going 'Code -> Preferences -> Settings'.

Search for "python formatting provider" and select "black" from the dropdown menu:

Hướng dẫn black, python vscode

In the settings, search for "format on save" and enable the "Editor: Format on Save" option:

Hướng dẫn black, python vscode

Black will now format your code whenever you save a *.py file.

Before saving:

Hướng dẫn black, python vscode

After saving:

Hướng dẫn black, python vscode


More: How to set Black line lengths in VSCode


Images from VSCode using Hyper Term Theme.

Hướng dẫn black, python vscode

To setup python black as a formatter for VS-Code workspace you need to install it on your virtual env or in your local python with the command:

$ pip install black

Now install the python extension for VS-Code, open your VS-Code and type “Ctrl + p”, paste the line below and hit enter:

ext install ms-python.python

We are almost there. Go to settings in your VS-Code typing “Ctrl + ,” or clicking at the gear on the bottom left and selecting “Settings [Ctrl+,]” option.

Hướng dẫn black, python vscode

Type “format on save” at the search bar on top of the Settings tab and check the box.

Hướng dẫn black, python vscode

Search for “python formatting provider” and select “black”.

Hướng dẫn black, python vscode

Now open/create a python file, write some code and save(Ctrl+s) it to see the magic happen!

Hướng dẫn black, python vscode

Example

Hướng dẫn black, python vscode

Before saving the file.

Hướng dẫn black, python vscode

After saving the code automatically get formatted

Hướng dẫn black, python vscode

Good to know: if Black is not working maybe your python code has some syntax error, recheck the code and test again.

Hướng dẫn black, python vscode

Contact me: linkedin.com/in/marco-belo/