Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic python source formatter

Tags:

I have a large body of python code that needs to have a pep8-compliant style/format imposed on it. There are variants of pep8 that various rules (like this one by a coworker), but the hardest thing is to deal with splitting too long lines and formatting the modified code.

I've looked up the questions on this:

  1. python-formatter-tool
  2. python-source-formatter-pretty-printer

They are from 2009 and 2010. I am hoping that better tools have been developed since then.

I know about PythonTidy which is pretty good but makes lots of code worse, IMHO. Pylint detects formatting errors but does not correct them. Web services are not really relevant to my requirements because I want a tool that can be part of a build.

Does anyone have a recommendation that has not already been covered? Thanks.

like image 396
hughdbrown Avatar asked Feb 11 '12 18:02

hughdbrown


People also ask

Which formatter is best for Python?

Black Formatter Black Formatter allows you to format your code using one of the most used Python formatters “Black”. Having a formatter in place improves productivity when working on Python projects with multiple developers.

Does prettier work for Python?

Prettier does not work with Python And don't forget to install and select the actual formatter that you want (just like in the official docs).

What is YAPF formatter?

YAPF takes a different approach. It's based off of 'clang-format', developed by Daniel Jasper. 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.


2 Answers

Another one that looks pretty decent: autopep8

But note that blindly following all the conventions in PEP8 isn't really in the spirit of PEP8. From PEP8 itself:

But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply.

like image 158
Mu Mind Avatar answered Sep 20 '22 04:09

Mu Mind


black is another contender. It's selling point is that is is barely configurable, so your team wastes less time quibbling about details.

There's an online demo here: black.now.sh

Side-note: black, yapf, and autopep8 have python language server plugins, so they integrate nicely with text editors including atom and vscode.

like image 28
Steven Kalt Avatar answered Sep 18 '22 04:09

Steven Kalt