Format Python Code Using YAPF
Introduction
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.
Installation
We install YAPF via pip
.
1 | $ 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
.
1 | $ sudo python3 -m pip uninstall pip |
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
1 | $ 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.
FAQs
Issues with Python 3 Code
It is possible that YAPF for Python 2 was installed. If the installation instruction above is not useful, we could also try installing YAPF for Python 3 using the following command.
1 | $ sudo apt install yapf3 python3-yapf |
The executable to use will be yapf3
instead of yapf
then.
References
Format Python Code Using YAPF