28

I was wondering if there exists a sort of Python beautifier like the gnu-indent command line tool for C code. Of course indentation is not the point in Python since it is programmer's responsibility but I wish to get my code written in a perfectly homogenous way, taking care particularly of having always identical blank space between operands or after and before separators and between blocks.

user127555
  • 381
  • 1
  • 3
  • 13
  • See also this question: https://stackoverflow.com/questions/9242748/programmatic-python-source-formatter – tricasse Jul 03 '14 at 19:15
  • Does this answer your question? [Programmatic python source formatter](https://stackoverflow.com/questions/9242748/programmatic-python-source-formatter) – Oliver Sieweke Mar 27 '20 at 13:49

6 Answers6

15

I am the one who asks the question. In fact, the tool the closest to my needs seems to be PythonTidy (it's a Python program of course : Python is best served by himself ;) ).

candide
  • 253
  • 4
  • 12
  • 1
    Thanks, I'm using PythonTidy now thanks to this, and it's proving useful. It uses the proper mechanism - i.e. the compiler.ast module to parse source into an AST, then walks the AST nodes getting them to write themselves out according to user-defined rules. The code is also very clear, so understanding and modifying its workings to suit my particular standards did not present much difficulty. Though I guess you'd expect clear code from someone who cares deeply enough about formatting to write an automated tool! 10/10 – Mike A Mar 01 '10 at 17:49
3

autopep8 attempts to automate making your code conform to pep8 coding standards

https://pypi.python.org/pypi/autopep8

tom
  • 2,335
  • 1
  • 16
  • 30
3

You can also try yapf:

A formatter for Python files

https://github.com/google/yapf/

Eyal Levin
  • 16,271
  • 6
  • 66
  • 56
1

PyLint has some formatting checks.

Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
1

Have you looked at pindent?

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
1

black is another recent option.

It provides deliberate and fast code formatting and is used by many projects such as pytest, SQLAlchemy and Pillow to name a few.

sgt pepper
  • 504
  • 7
  • 15