In this tutorial, we will setup Python linting and automatic code formatting in VSCode. We will use
pylint to highlight linting errors and
black for auto-formatting our code on save.
black could help speed up development, reduce time spent upskilling new hires, and make your diffs easier to read for code reviews.
First, let's start by making a new virtual environment for this tutorial called
conda create -y -n python-linting python=3.8 conda activate python-linting
Next, we'll make sure that we have our linter and formatter installed.
conda install -y pylint black
Now that we have our tools installed, we can move on to setting them up in VSCode.
To enable linting for Python in VSCode, we need to make sure some things are enabled in our settings. Be sure to make these changes to the "User" level (as opposed to the Workspace or folder only) so that it takes effect in any project.
First, open your VSCode Settings UI and search for "Python linting". Make sure that the following setting is checked:
Python > Linting: Enabled
[x]Whether to lint Python files.
Also specifically allow
pylint linting by making sure the following setting is checked:
Python > Linting: Pylint Enabled
[x]Whether to lint Python files using pylint.
You can optionally suppress "convention"-level linting messages if you want to only highlight more egregious issues. To disable convention messages, add
--disable=C to the
Python > Linting: Pylint Args
Only do this part if you know that you don't want convention linting errors shown.
To setup auto-formatting, we need to tell VSCode to use
black as our formatter for Python code. We can do this in our settings by selecting
black from the following dropdown selector:
Python > Formatting: Provider
Next, we need to tell VSCode that we'd like to auto-format our code on save of the file. We can do this with the
Format on Save option:
Editor: Format on Save
[x]Format a file on save. A formatter must be available, the file must not be saved after delay, and the editor must not be shutting down.
If everything went well, you should get helpful linting messages while you code and automatic code formatting each time you save your file.
In this tutorial, we setup
black for Python linting and auto-formatting in VSCode. Linting and auto-formatting can help speed up development by removing time spent debugging and thinking about formatting. They can also help a team of developers work together by enforcing a reasonable set of standards that strive to make their codebase and pull requests easier to read and review.
All source materials for this article are available here on my blog GitHub repo.