Search code examples
pythoncoding-stylepep8

Tool to convert Python code to be PEP8 compliant


I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both an online service and a python module.

However, I cannot find a service or module which can convert my Python file to a self-contained, PEP8 valid Python file. Does anyone know if there are any?
I assume it's feasible since PEP8 is all about the appearance of the code, right?


Solution

  • 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!