Logo

dev-resources.site

for different kinds of informations.

How to Configure VSCode for Auto Formatting and Linting in Python

Published at
1/8/2025
Categories
vscode
python
linting
formatting
Author
jajera
Categories
4 categories in total
vscode
open
python
open
linting
open
formatting
open
Author
6 person written this
jajera
open
How to Configure VSCode for Auto Formatting and Linting in Python

How to Configure VSCode for Auto Formatting and Linting in Python

While VSCode is a popular choice for many Python developers due to its flexibility and powerful features, it is just one of many tools available for code editing and automation. Developers may prefer other IDEs or editors like PyCharm, Sublime Text, or even Vim, depending on their workflow. This guide focuses on VSCode to demonstrate how you can set up auto formatting and linting, but similar principles may apply to other tools.

Python developers love clean and readable code, and tools like VSCode make it easy to achieve this through auto formatting and linting. In this guide, we'll show you how to configure VSCode for Python formatting and linting using configuration files and CLI commands to ensure automation and avoid manual intervention.


Why Auto Formatting and Linting?

  • Auto Formatting ensures consistent code style, adheres to PEP 8, and saves time spent on manual adjustments.
  • Linting identifies syntax errors, unused imports, and other potential issues early in the development process.

Together, they help maintain high code quality and reduce bugs.


Required Tools for Formatting and Linting

To format and lint your Python code effectively, you need the following tools:

Black (Formatting)

  • Purpose: Black is an opinionated code formatter that ensures consistent style automatically, adhering to PEP 8.
  • Key Features: Simplifies code formatting and removes manual adjustments.
  • Install: Run pip install black

pylint (Linting)

  • Purpose: pylint analyzes Python code to identify errors, enforce coding standards, and highlight potential issues like unused imports or undefined variables.
  • Key Features: Detects errors and enforces best practices.
  • Install: Run pip install pylint

Automating Configuration with Black and pylint

Below is an explanation of the relevant settings.json configurations:

  • editor.formatOnSave: Automatically formats your code whenever you save a file.
  • editor.formatOnPaste: Formats pasted code to match the project's coding style.
  • editor.tabSize: Defines the number of spaces equivalent to a tab.
  • editor.insertSpaces: Converts tabs to spaces for consistent indentation.
  • files.eol: Sets the default end-of-line character to for compatibility.
  • files.trimTrailingWhitespace: Removes unnecessary spaces at the end of lines.
  • files.trimFinalNewlines: Removes extra newlines at the end of files.
  • files.insertFinalNewline: Ensures there is one final newline at the end of files.
  • python.formatting.provider: Specifies the formatter to use, in this case, Black.
  • python.formatting.blackArgs: Passes configuration arguments to Black, such as specifying a pyproject.toml file.
  • python.linting.enabled: Enables linting for Python files.
  • python.linting.flake8Enabled: Activates the flake8 linter.
  • python.linting.mypyEnabled: Activates the mypy static type checker.
  • python.linting.flake8Args: Passes arguments to flake8, such as a configuration file.
  • python.analysis.extraPaths: Adds extra paths for Python module resolution.
  • python.pythonPath: Specifies the Python interpreter path for your project.
  • [python]: Overrides editor settings specifically for Python files, such as the default formatter.

Update VSCode Settings Programmatically

Create or update the settings.json file in your .vscode directory:

{
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true,
  "editor.tabSize": 4,
  "editor.insertSpaces": true,
  "files.eol": "\n",
  "files.trimTrailingWhitespace": true,
  "files.trimFinalNewlines": true,
  "files.insertFinalNewline": true,
  "python.formatting.provider": "black",
  "python.formatting.blackArgs": ["--line-length=79"],
  "python.linting.enabled": true,
  "python.linting.flake8Enabled": true,
  "python.linting.mypyEnabled": true,
  "python.linting.flake8Args": ["--show-source"]
  "python.analysis.extraPaths": [
    "./src"
  ],
  "python.pythonPath": "/workspaces/test/.venv/bin/python",
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  }
}
Enter fullscreen mode Exit fullscreen mode

Adding Recommended Extensions

To enhance team-wide consistency and ensure all members use the necessary tools, you can add an extensions.json file directly to your project. Note that this file will not automatically install the extensions but will flag and recommend them when you open the project in VSCode. Make sure to accept the recommendations for the extensions to install.

{
  "recommendations": [
    "ms-python.python",
    "ms-python.black-formatter",
    "ms-python.pylint"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Save this file in the .vscode directory as extensions.json.


Visual Representation of Configuration Files

Here’s a breakdown of the files and their purposes:

File Purpose
.vscode/settings.json Defines project-specific settings for formatting and linting behavior.
.vscode/extensions.json Recommends extensions for team-wide consistency in the development IDE.

Directory Structure Example

.vscode/
β”œβ”€β”€ settings.json   # Configures formatting and linting behavior
β”œβ”€β”€ extensions.json # Recommends extensions for VSCode
Enter fullscreen mode Exit fullscreen mode

Testing Your Configuration

Formatting and Linting Examples

  1. Code with Issues:
   import os

   def example_function():
           print ( "Hello World" )
   print(undefined_variable)
Enter fullscreen mode Exit fullscreen mode
  1. After Running Black:
   import os

   def example_function():
       print("Hello World")

   print(undefined_variable)
Enter fullscreen mode Exit fullscreen mode
  1. After Running pylint: Warnings flagged:
    • Unused import: os
    • Undefined variable: undefined_variable

Using Black and pylint Together

Why Combine Black and pylint?

  • Black ensures consistent formatting and adheres to PEP 8 automatically.
  • pylint identifies code issues like unused imports, undefined variables, and enforces coding standards.

Workflow with Both Tools

Update settings.json:

{
  "editor.formatOnSave": true,
  "editor.formatOnPaste": true,
  "editor.tabSize": 4,
  "editor.insertSpaces": true,
  "files.eol": "\n",
  "files.trimTrailingWhitespace": true,
  "files.trimFinalNewlines": true,
  "files.insertFinalNewline": true,
  "python.formatting.provider": "black",
  "python.formatting.blackArgs": ["--line-length=79"],
  "python.linting.enabled": true,
  "python.linting.flake8Enabled": true,
  "python.linting.mypyEnabled": true,
  "python.linting.flake8Args": ["--show-source"],
  "python.linting.pylintEnabled": true,
  "python.linting.pylintArgs": ["--disable=C0114,C0115,C0116"],
  "python.analysis.extraPaths": [
    "./src"
  ],
  "python.pythonPath": "/workspaces/test/.venv/bin/python",
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true
  }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Configuring VSCode for auto formatting and linting using settings.json and CLI commands ensures a seamless and consistent development workflow. By avoiding manual steps and leveraging automation, you can focus on writing high-quality Python code without worrying about formatting or linting issues.

For a working example of this setup, check out this repository: vscode-python-lint-formatter.

Happy coding!

vscode Article's
30 articles in total
Favicon
Master Azure Development: Linking Cloud Shell with VS Code on Windows Made Easy
Favicon
Mega Menu Breaks, CSS3
Favicon
No Copilot? No Problem! Get Free AI in VSCode Now
Favicon
🌟 How to Fix Node.js Path Issues in VS Code (Step-by-Step Guide)
Favicon
Rendering Shopify Liquid Code Locally with VS Code
Favicon
How This VSCode Extension Saves Your Code from Exposed Secrets?
Favicon
Visual Studio Code Extension for Developers
Favicon
How to Configure VSCode for Auto Formatting and Linting in Python
Favicon
Was able to get my terminal looking nice thanks to this post!
Favicon
Context vs. State: Why Context is King in Software Systems
Favicon
Day 7 : C++ language | Comparison Operators
Favicon
Day 5: C++ language | Arithmetic Operators
Favicon
Day 6: C++ Language | Assignment operators
Favicon
Essential custom instructions for GitHub Copilot
Favicon
Just posted on my top 5 VSCode shortcuts :)) Hoping it helps people who might just get into it :))
Favicon
My text editor setup in 2025 and how I came out of extension hell
Favicon
Oh bless me, Father, I have done something unholy: Installing .NET Core on Apple Silicon
Favicon
Day 3: C++ language | Variables | Datatypes | Part-1
Favicon
VSCode Prettier format on save
Favicon
What I Learned Today
Favicon
🌈 Change workspace project color and name in vscode
Favicon
Git: haz que todos amen leer tus commits
Favicon
Unlock Free Microsoft Resources to Supercharge Your Tech Journey πŸš€
Favicon
Building a Privacy-First Coding Activity Tracker for VS Code
Favicon
.NET Development Essentials on macOS with VS Code
Favicon
Unlocking the Potential of Visual Studio Code for Web Development Projects
Favicon
Troubleshooting Docker credsStore Auto-Configuration Issues in VS Code Dev Containers
Favicon
How to install vscode in android
Favicon
Introducing Inline Cryptography Toolkit: Simplify Encryption, Decryption, and Hashing in VS Code πŸš€
Favicon
Zed IDE vs. NeoVim and Other IDEs: The Future of Modern Coding Environments

Featured ones: