Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

formatting - How do I autoformat some Python code to be correctly formatted?

I have some existing code which isn't formatted consistently -- sometimes two spaces are used for indent, sometimes four, and so on. The code itself is correct and well-tested, but the formatting is awful.

Is there a place online where I can simply paste a snippet of Python code and have it be indented/formatted automatically for me? Alternatively, is there an X such that I can do something like X --input=*.py and have it overwrite each file with a formatted version?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

autopep8

autopep8 would auto-format your python script. not only the code indentation, but also other coding spacing styles. It makes your python script to conform PEP8 Style Guide.

pip install autopep8
autopep8 your_script.py    # dry-run, only print
autopep8 -i your_script.py # replace content

Update:

Many editors have pep8 plugins that automatically reformat your code right after you save the file. py-autopep8 in emacs

yapf

yapf is a new and better python code formatter. which tries to get the best formatting, not just to conform the guidelines. The usage is quite the same as autopep8.

pip install yapf
yapf your_script.py    # dry-run, only print
yapf -i your_script.py # replace content

For more information, like formatting configurations, please read the README.rst on yapf github


Update 2:

Black

Black is much better than yapf. It's smarter and fits most complex formatting cases.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...