Lei Mao bio photo

Lei Mao

Machine Learning, Artificial Intelligence, Computer Science.

Twitter Facebook LinkedIn GitHub   G. Scholar E-Mail RSS


To format C and C++ code, we often use Clang-Format. Recently I downloaded a couple of Python projects from Google’s GitHub, and I found that Google’s standard is to use 2-space indentation while my preference is to use 4-space indentation. Then the question is how to parse the Python projects so that it uses 4-space indentation. I tried to do it in Visual Studio Code but found no solutions. A naive way is to replace the 2-space string to 4-space string. However, this might introduce some unexpected problems.

Somehow I found Google has an open source tool YAPF for Python formatting. Its usages are very similar to Clang-Format, and its documentation is better than the Clang-Format’s documentation in my opinion. Since the YAPF’s documentation is self-explanatory, in this blog post I will just document some simple usages redundantly.


We install YAPF via pip.

$ pip install yapf

However, if somehow the OS requires you to add --user in order to install, you would likely have problems in using YAPF from the terminal. To solve this problem, in my case, we reinstall pip3.

$ sudo python3 -m pip uninstall pip
$ sudo apt install python3-pip --reinstall -y
$ source ~/.bashrc

Then we should be able to install YAPF for all users without having to specify --user.

Simple Usages

Use 4-Space Indentation in All Python Files

$ yapf --in-place --recursive --style="{indent_width: 4}" *.py
  • --in-place is to make modifications in-place to all the Python files, make sure you are aware of this and backup all the files before formatting.
  • --style is to indicate what style details should we use. Just like Clang-Format, if we have a style file in the directory, this argument does not have to be supplemented.
  • --recursive is to recursively go through the directory and its subdirectory.