I was writing Python code and encountered issues with formatting. These formatting problems can complicate code reviews and the use of automated tools to detect such issues. Fortunately, life becomes much easier when you integrate a formatter into your code editor to automatically fix those issues upon saving. Here’s how to do it:

  1. First, install Google’s yapf formatter:

    pip install yapf
    
  2. Next, open your Visual Studio Code editor. Press “Command + Shift + P” if you’re using a Mac, or “Ctrl + Shift + P” if you’re on Linux. Type “Open settings (JSON)” in the search bar and add the following line:

    "python.formatting.provider": "yapf"
    
  3. If you want your code to auto-format upon saving, rather than merely receiving tips within the editor, add this setting as well:

    "editor.formatOnSave": true
    
  4. Optionally, if you wish to use your project’s .style.yapf instead of the global styles, add the following line:

    "python.formatting.yapfArgs": ["--style", ".style.yapf"]
    

Now you can test the auto-formatting feature. For example, if you don’t have a new line at the end of your Python file and then you save it, the formatter will automatically correct this issue for you.