I recently decided to adhere PEP 8 more strictly (i.e. going from 3 blanks to 4). I ran into some problem with diffing python files ignoring insignificant whitespace.
I went through some old code and used flake8 and autopep8 with great success to clean it up.
I was a bit afraid that while manually indenting lines I would break some indention.
A git diff -u file.py
was of little use because naturally this process left few lines untouched.
A git diff -uw file.py
also filters the significant changes in whitespace.
Let’s consider the follwing example prime_wrong.py
def check_prime(n): i = 2 while i * i <= n: if n % i == 0: print(n, 'is not prime') break i += 1 else: print(n, 'is prime')
versus the original prime.py:
def check_prime(n): i = 2 while i * i <= n: if n % i == 0: print(n, 'is not prime') break i += 1 else: print(n, 'is prime')
How do I find the significant change? There once was a project called ydiff but it looks like it meanwhile dropped python support. PrettyDiff sounds promising but does not support python.
Let's assume we trust autopep8. Then we can use it to normalize our python source and define a diff command (in bash) as
function pydiff() { diff -u <(autopep8 "$1") <(autopep8 "$2") }
et voilÃ
$ pydiff prime.py prime_wrong.py --- /dev/fd/63 2017-03-22 22:11:23.876892817 +0100 +++ /dev/fd/62 2017-03-22 22:11:23.876892817 +0100 @@ -4,7 +4,7 @@ while i * i <= n: if n % i == 0: print(n, 'is not prime') - break + break i += 1 else: print(n, 'is prime')
The good thing about PEP 8 is that there is almost no insignificant whitespace anymore so you rarely have to diff -uw
.
If you want to diff with the HEAD version using git:
function git-pydiff () { if [ ! -f "$1" ] ; then echo "$1 not found" ; return 1 ; fi diff -u <(git show HEAD:$(git ls-tree --full-name --name-only HEAD "$1") | \ autopep8 - ) <(autopep8 "$1") } git-pydiff prime.py
Homework: make that a proper git alias / script.
Tell me, if you know better solutions to those problems.