Hi, I'm Harlin and welcome to my blog. I write about Python, Alfresco and other cheesy comestibles.

Python - PEP 8 Series - Whitespace

Python is one of the few languages out there which takes whitespace into consideration for the purpose of readabilty. This is why this code is more elegant and flowable as you type:

def add_and_double(num1, num2):
    addition = num1 + num2
    product = addition * 2
    return product

vs

public int (int num1, int num2) {
    int addition = num1 + num2;
    int product = addition * 2;
    return product;
}

Well, at least that's my opinion ;-) but whitespace in the wrong places make for less readability. Keep in mind you can also use ";" to end statements in Python like in Java or JavaScript but they are generally discouraged.

First off, inside parenthesis, we don't want extra white space:

Bad:

def add_double_expo( num1, num2 ):
    ...

Good:

def add_double_expo(num1, num2):
    ...

Using braces for list elements:

Bad (but valid for the interpreter):

other_nums = '5 3 1'
nums = other_nums.split()
print( nums [ 0 ] )
print( nums [ 1 ] )
print( nums [ 2 ] )

Good:

other_nums = '5 3 1'
nums = other_nums.split()
print(nums[0])
print(nums[1])
print(nums[2])

Single value lists:

Bad:

single = (0, )

Good:

single = (0,)

Commas in a list:

Bad:

for k,v in kwargs.items():
    print(k,v)

Good:

for k, v in kwargs.items():
    print(k, v)

Give some space for variable assignments:

num1 = 0
num2 = 5

But it's ok to not use space when assigning to optional variables in a function signature:

person = Person()
person(
    name='Harlin',
    age=48,
    height='short'
)

Lastly, avoid trailing whitespace anywhere in your code. You may not be able to see it in your editor but it is possible for trailing whitespace to affect your code being interpreted.

Any Comments, Always Welcome!