Python Code Style Guide: Write readable code

Python Code Style Guide: Write readable code

code is read much more often than it is written.

You must make your code readable so when someone else or you after a month sees your code you know what it's doing.

Style Guides

Indentation

Use 4 spaces per indentation level.

  1. Example when calling the function
# Correct:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

# Incorrect
foo = long_function_name(var_one, var_two,
    var_three, var_four)    # No allignment

Wrong and Recommendation

  1. Example when creating function

     # correct
     def long_function_name(
             var_one, var_two, var_three,
             var_four):
         print(var_one)
    
     # Correct
     def long_function_name(
             var_one, var_two, 
             var_three,var_four):
         print(var_one)
    
     # Incorrect
     # Further indentation required as indentation is not distinguishable.
     def long_function_name(
         var_one, var_two, var_three,
         var_four):
         print(var_one)
    

    Wrong and Recommendation

IF Statement

# No extra indentation.
if (this_is_one_thing and
    that_is_another_thing):
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
        and that_is_another_thing):
    do_something()

# Both of above are recommended method when using if statements

Brackets

# Choice 1
my_list = [
    1, 2, 3,
    4, 5, 6,
    ]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
    )
# Choice 2

my_list = [
    1, 2, 3,
    4, 5, 6,
]
result = some_function_that_takes_arguments(
    'a', 'b', 'c',
    'd', 'e', 'f',
)

# Both are recommended

Maximum Line length

You should Limit all lines to a maximum of 79 characters.

# words were more than 79 char
with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Line Break Before or After Binary operators

# Wrong:
# operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

# Correct:
# easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

Imports

# Correct:
import os
import sys

# Wrong:
import sys, os

# Correct:
from subprocess import Popen, PIPE

# correct
import mypkg.sibling
from mypkg import sibling
from mypkg.sibling import example

Whitespaces

# Correct:
spam(ham[1], {eggs: 2})

# Wrong:
spam( ham[ 1 ], { eggs: 2 } )

# Correct:
if x == 4: print(x, y); x, y = y, x

# Wrong:
if x == 4 : print(x , y) ; x , y = y , x
# Correct:
ham[1:9], ham[1:9:3], ham[:9:3], ham[1::3], ham[1:9:]
ham[lower:upper], ham[lower:upper:], ham[lower::step]
ham[lower+offset : upper+offset]
ham[: upper_fn(x) : step_fn(x)], ham[:: step_fn(x)]
ham[lower + offset : upper + offset]

# Wrong:
ham[lower + offset:upper + offset]
ham[1: 9], ham[1 :9], ham[1:9 :3]
ham[lower : : step]
ham[ : upper]
# Correct:
spam(1)
# Wrong:
spam (1)
# Correct:
dct['key'] = lst[index]

# Wrong:
dct ['key'] = lst [index]
# Correct:
x = 1
y = 2
long_variable = 3

# Wrong:
x             = 1
y             = 2
long_variable = 3
  • Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), Booleans (and, or, not).
# Correct:
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

# Wrong:
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)
  • when to not use space with =
# Correct:
def complex(real, imag=0.0):
    return magic(r=real, i=imag)

# Wrong:
def complex(real, imag = 0.0):
    return magic(r = real, i = imag)

Compound statements

# Correct:
if foo == 'blah':
    do_blah_thing()
do_one()
do_two()
do_three()

# Wrong:
if foo == 'blah': do_blah_thing()
do_one(); do_two(); do_three()

Trailing commas

# Correct:
FILES = ('setup.cfg',)

# Wrong:
FILES = 'setup.cfg',

# Correct:
FILES = [
    'setup.cfg',
    'tox.ini',
    ]
initialize(FILES,
           error=True,
           )

# Wrong:
FILES = ['setup.cfg', 'tox.ini',]
initialize(FILES, error=True,)

Naming Conventions

  • Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single-character variable names.

  • Class Names should normally use CapWords Convention e.g class Student or class StudentClearance .

  • Exception names should use the same as the Class Names convention.

  • Function names should be lowercase, with words separated by an underscore e.g. is_even() .

  • The variable name follows the same convention as functions e.g count = 0

  • Constants should be written in all capital letters with underscores separating words e.g MAX or TOTAL.

Conclusion

These are the rules but even without this when you see your code, its spacing, naming and indentation you can tell what looks better and what not.
Please comment to share your reviews.