DEV Community

John  Ajera
John Ajera

Posted on

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!

Top comments (0)