📜 ⬆️ ⬇️

Yapf - we brush the code of Python with autocorrector

In an era of increasing popularity of various js and css linter'ov, it is not surprising the emergence of a convenient auto-correction linter for Python.

Greet, Yapf is a ready-made solution for turning porridge from strings into quite readable code. And believe me, it will come in handy.

image

Most modern Python linters — for example, autopep8 and pep8ify — are made to remove errors in the code. This has some obvious limitations. For example, code that conforms to PEP8 cannot be reformatted. But this does not mean that the code looks good.
')
YAPF takes a different approach. It is based on the “clang-format” developed by Daniel Jasper. In essence, the algorithm takes the code and reformats it into a format that matches the style of the manual, even if the source code does not violate the style manual. The idea is also similar to the gofmt tool for the Go programming language: the end of all holy wars about formatting - if the entire project codebase is simply pumped through YAPF whenever changes are made, the style remains consistent throughout the project, and there is no point in arguing about the style in each review code.

The ultimate goal is that the python code with YAPF is written as well as the code that a programmer could write if he followed the style guide. This eliminates the hard work of maintaining the code.

And now for the practical part:

YAPF can be used both from the command line and as a text editor plugin. There are now plugins for Emacs, VIM and Sublime Text.

I mainly use Sublime Text, so I'll show you how to configure it to use YAPF.
Sublime Text Plugin - github.com/jason-kane/PyYapf

1. Installation.

pip install yapf 

Install Sublime Package Control by following the instructions here (if you have not already done so).

Ctrl-Shift-P (Mac: Cmd-Shift-P) and select "Package Management: Install Package."

Find PyYapf Python Formatter in the list.

2. Setup.

After installation, you will have PyYapf in the settings menu.

image

To make it work, you need to specify where you have the Yapf file (in my case, it was in the Python folder)

Open the settings PyYapf - Settings default, copy them. Then open PyYapf - Settings User, paste the copied rules and specify the path to the Yapf file.

image

After that, you can already use YAPF to format the code. Press Ctrl-Alt-F and the code will be converted. The default settings are PEP8.

An example before and after.

image

You can set many rules in it. YAPF allows you to make flexible settings for various parameters, more details here - https://github.com/google/yapf#id8

I hope YAPF will help you write beautiful and clean code that meets numerous standards.

Source: https://habr.com/ru/post/324336/


All Articles