Videos
Is it safe to paste my Python code into an online formatter?
HTTPS and processed transiently for formatting. However, as a best practice you should avoid sending passwords, API keys, personal data or highly confidential business logic to any online tool. For sensitive projects, run Black locally or inside your own CI environment instead.Will the Python formatter change how my code behaves?
What line length should I choose when formatting Python code?
You can use autopep8! Whilst you make yourself a cup of coffee this tool happily removes all those pesky PEP8 violations which don't change the meaning of the code.
Install it via pip:
pip install autopep8
Apply this to a specific file:
autopep8 py_file --in-place
or to your project (recursively), the verbose option gives you some feedback of how it's going:
autopep8 project_dir --recursive --in-place --pep8-passes 2000 --verbose
Note: Sometimes the default of 100 passes isn't enough, I set it to 2000 as it's reasonably high and will catch all but the most troublesome files (it stops passing once it finds no resolvable pep8 infractions)...
At this point I suggest retesting and doing a commit!
If you want "full" PEP8 compliance: one tactic I've used is to run autopep8 as above, then run PEP8, which prints the remaining violations (file, line number, and what):
pep8 project_dir --ignore=E501
and manually change these individually (e.g. E712s - comparison with boolean).
Note: autopep8 offers an --aggressive argument (to ruthlessly "fix" these meaning-changing violations), but beware if you do use aggressive you may have to debug... (e.g. in numpy/pandas True == np.bool_(True) but not True is np.bool_(True)!)
You can check how many violations of each type (before and after):
pep8 --quiet --statistics .
Note: I consider E501s (line too long) are a special case as there will probably be a lot of these in your code and sometimes these are not corrected by autopep8.
As an example, I applied this technique to the pandas code base.
Unfortunately "pep8 storming" (the entire project) has several negative side-effects:
- lots of merge-conflicts
- break git blame
- make code review difficult
As an alternative (and thanks to @y-p for the idea), I wrote a small package which autopep8s only those lines which you have been working on since the last commit/branch:
Basically leaving the project a little better than you found it:
pip install pep8radius
Suppose you've done your work off of master and are ready to commit:
# be somewhere in your project directory
# see the diff with pep, see the changes you've made since master
pep8radius master --diff
# make those changes
pep8radius master --diff --in-place
Or to clean the new lines you've commited since the last commit:
pep8radius --diff
pep8radius --diff --in-place
# the lines which changed since a specific commit `git diff 98f51f`
pep8radius 98f51f --diff
Basically pep8radius is applying autopep8 to lines in the output of git/hg diff (from the last shared commit).
This script currently works with git and hg, if your using something else and want this to work please post a comment/issue/PR!
I am searching for a formatter for Python3 which takes a few simple styling parameters and yet is very easy to use. All I found so far where tons of formatters, which ansolutely enforce one and only one formatting style.
Example input:
def deleteSubnet(ipAddress, cidrMask, interface = defaultNetworkInterface):
if subprocess.run(["ip","a","d",ipAddress+"/"+cidrMask,"dev",interface], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode != 0:
quit(color.red+" ERROR:"+color.stop+" IP could not be cleared. You need to manually remove "+color.blue+ipAddress+"/"+cidrMask+color.stop+" from "+color.blue+interface+color.stop+"!!! Terminating...")
print(color.green+" Success: deleted IP "+color.stopcolor.blue+ipAddress+"/"+cidrMask+color.stop+" from interface "+color.blue+interface+color.stop+".")Example output (NOT WANTED):
def deleteSubnet(ipAddress, cidrMask, interface=defaultNetworkInterface):
if (
subprocess.run(
["ip", "a", "d", ipAddress + "/" + cidrMask, "dev", interface]
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
).returncode
!= 0
):
quit(
color.red
+ " ERROR:"
+ color.stop
+ " IP could not be cleared. You need to manually remove "
+ color.blue
+ ipAddress
+ "/"
+ cidrMask
+ color.stop
+ " from "
+ color.blue
+ interface
+ color.stop
+ "!!! Terminating..."
)
print(
color.green
+ " Success: deleted IP "
+ color.stopcolor.blue
+ ipAddress
+ "/"
+ cidrMask
+ color.stop
+ " from interface "
+ color.blue
+ interface
+ color.stop
+ "."
)Yes it is ugly. Does not matter. If reddit does word-wrap the lines, it will be horrible. But if the line just overflows, it just looks great for me.
All I want to do is a simple tool that understands the indentations and allows me to configure a target indentation. I do not care for the standard that tools like pylint try to enforce - i dislike it.
However what is way worse than not breaking lines, is uneven indentations. And that I need to fix - but please not manually. Is there an easy to use tool, that can fix my *variable* indentations to exactly 2 spaces per indent without changing the rest of the content of the lines? (yes I want 2 spaces, period)
For javascript there are amazing tools, like beautifier.io which handles it perfectly. Why can't I find something like that for python? And yes, I prefer a simple online tool actually, that does not require a login or download.
As to why it is uneven: It is a copy&paste collection from different sources.
Thanks for your help.
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.
Edit: Nowadays, I would recommend autopep8, since it not only corrects indentation problems but also (at your discretion) makes code conform to many other PEP8 guidelines.
Use reindent.py. It should come with the standard distribution of Python, though on Ubuntu you need to install the python2.6-examples package.
You can also find it on the web.
This script attempts to convert any python script to conform with the 4-space standard.