hughdbrown
hughdbrown

Reputation: 49033

Programmatic python source formatter

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.

Upvotes: 20

Views: 5091

Answers (5)

Steven Kalt
Steven Kalt

Reputation: 1198

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.

Upvotes: 3

Håken Lid
Håken Lid

Reputation: 23064

Google's yapf works very well.

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

You can integrate it into your workflow and run it when you save files in your editor or as a git precommit hook or something like that.

Upvotes: 2

Muhd
Muhd

Reputation: 25606

PyCharm has this functionality built in and now has a free, open source community edition. Open your file up in it and hit CtrlAltL.

Unifortunately, it will not also automatically refactor function names and variable names to PEP8 convention... those will have to be done one by one with PyCharm's rename functionality.

Upvotes: 2

zzart
zzart

Reputation: 11483

PythonTidy seems to be splitting lines quite well http://www.lacusveris.com/PythonTidy/

Upvotes: 1

Mu Mind
Mu Mind

Reputation: 11204

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.

Upvotes: 7

Related Questions