This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Good Python Coding Style

Python’s design philosophy encompasses many facets, one of which is readability.

In you are interested, you can read the “The Zen of Python” by doing this:

>>> import this

Python Enhancement Proposal (PEP) 8 provides guidelines on how to write (good) Python code in order to improve readability and consistency.

We have discussed some of this with regards to naming variables.

We will summarise a few more here.

Lines should be limited to 79 characters.

Use implicit line continuation inside parenthesis, brackets, and braces to break your code up to several lines. You can also use backslash \ if implicit line continuation is not possible.

my_list = [
    1, 2, 3,
    4, 5, 6,
]

result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

Prefer your line breaks before your operators rather than after.

[Josiah says: “I was not even aware of this until now!”]

# Bad
total = (first_var + 
         second_var - 
         third_var)

# Good
total = (first_var 
         + second_var
         - third_var)

However, the guide also says:

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth’s style [breaking before operators] is suggested.

Indentation

PEP 8 recommends using four spaces for indenting your code blocks.

[Josiah ignores this guideline with pride, and uses tabs.]

Whitespace issues

Do not align assignment operators.

# Bad:
x             = 1
y             = 2
long_variable = 3

# Good:
x = 1
y = 2
long_variable = 3

Avoid whitespace immediately before the open parenthesis (e.g. functions) or square brackets (indexing/slicing)

# Bad:
spam (1)
dct ['key'] = lst [index]

# Good:
spam(1)
dct['key'] = lst[index]

The section on whitespace on PEP8 has more examples. Even Josiah is not aware of some of these!

Do not have two disjoint statements on the same line

# Bad:
if x == 1: print(x)

# Good:
if x == 1:
    print(x)

Do not compare boolean expression to True/False using the equality operator

# Bad: 
if (x > 2) == True:
    print("yes")

# Good:
if x > 2:
    print("yes")

Checking for None

Are you checking whether a variable is True or whether it is pointing to an object (that is not None)? Make sure you know the differences between these.

Also remember that all these values are also considered False: 0, "", [], (), {}.

# Bad:
if var:
    print(var)

# Good:
if var is not None:
    print(var)

Use is not rather than not ... is

# Bad
if not x is None: 
    print(x)

# Good
if x is not None:
    print(x)

Do not use list comprehension to print

# Bad
[print(x) for x in range(3)]

# Good
for x in range(3): 
    print(x)

Use the in operator instead of checking a variable against several values

# Bad
if capital == 'London' or capital == 'Paris' or capital == 'Rome': 
    found = True

# Good 
found = capital in {'London', 'Paris', 'Rome'}

It is about consistency and readability

Keep in mind that these are guidelines, and not rules.

Use your judgement if you feel that there is a good reason to ignore the guidelines.

However, know when to be inconsistent – sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!

PyCodeStyle

You can check whether your code conforms to PEP8 with the command line utility pycodestyle. You can install this using pip install pycodestyle.

Prepare a script (say test.py) that does not conform to PEP8 (for example using two spaces or tabs for indentation).

Run pycodestyle test.py

test.py:3:3: E111 indentation is not a multiple of four
test.py:4:3: E111 indentation is not a multiple of four