Code formatting is effort to makes code easier to read by human by applying specific rules and conventions for line spacing, indents, spacing around operators, and so on see more details here. Formatting shouldn't affect the functionality of the code itself.
On the other hand, linting is made to analyzes code for common syntactical, stylistic, and functional errors as well as unconventional programming practices that can lead to errors. Although there is a little overlap between formatting and linting, the two capabilities are complementary.)
An auto formatter is a tool to automatically format your code in a way it complies to the tool or any other standard it set. Normally there's 2 option when we want to integrate this tool on our workflow. First is through your favourite text-editor and second is using pre-commit hook. In this article i will explain more about the first option which integrate auto formatter in our text-editor for better code standard. Advantage of using auto formatter are :
- You don't worry about low-level problems since it's fixed automatically
- Reduces number of discussions or debate about code style so developer can focus writing actual code
- Help new developers more familiar with the code base because the style is consistent
- Less merge conflicts
In Python there are three auto-formatter available:
autopep8 is an open source auto formatter built and made by several developers. It uses pycodestyle to analyze which parts of your code do not fit to the pep-guidelines and will try to fix them. As of the time of writing the project had around 3.3K stars (April 2020).
Yet another Python formatter is tool produced and maintained by Google. It has ~10.5K stars (April 2020) on GitHub. Yapf follow different approach compare with other auto formatter tools.
In essence, the algorithm takes the code and reformats it to the best formatting that conforms to the style guide, even if the original code didn't violate the style guide. Style remains consistent throughout the project and there's no point arguing about style in every code review.
In order to get started you just need to install one of package above.
pip install autopep8 autopep8 --in-place --aggressive --aggressive <filename>
pip install yapf yapf <filename>
pip install black black <filename>
What is your favourite Python Auto-Formatter?. Let me know by adding comment below :)