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 apt
on Ubuntu.
1 | $ sudo apt update |
Simple Usages
Use 4-Space Indentation in All Python Files
1 | $ yapf3 --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.
References
Format Python Code Using YAPF