How to Write Human Readable Code

A comprehensive summary
A talk
10 practices for readable code
The junior developer’s guide to writing super clean and readable code
3 creative techniques for writing modular code

There is no need to over-explain why writing human readable code is important. A human readable code is crucial for development, maintenance and reusing. Above are several posts talking about how to write the human readable code, and some examples for practice is provided below.

Modular Code

Avoid large block.

Using variables to isolate logical expressions

In [1]:
i = 1
a_list = [2, 3]
even = i % 2
small_list = len(a_list) < 10

if even and small_list:

Using nested functions to encapsulate blocks of code

This is pretty useful when writing tutorial code. In any place you want to write a comment, you can write it as a function with appropriate name.

In [2]:
def shopping():
    def buy_milk():

    def buy_egg():

    def buy_paper_towel():

Preventing data access with block-scoped variables

If a variable only plays role in a block, it should not appear outside the block.

In [3]:
import numpy as np

a = np.random.randint(10)

# right
if a % 2 == 0:
    b = 3
    a += b

# wrong
b = 3
if a % 2 == 0:
    a += b

Use variable names that explain themselves

In [4]:
a = 22  # bad
age = 22  # good

Once you know where you want to go, refactor

A nice talk

Formatting & Indentation

Automated Code Formating Tools - Jupyter, JetBrains IDEs

Coding Style

Google python coding style guide
A good IDE can help you check the style, I am satisfied with JetBrains IDEs.

E.g., to help people distinct the class, package, constant, variable, python usually follow the following style.

In [5]:
# Usually class uses Camel name and with captial initial letter
# Wrong
class good_boy:

# Right
class GoodBoy:
In [6]:
# package use snake case in general, it is better to have only one word
import async_timeout
import numpy as np
In [7]:
# Constant, captial snacke case
In [8]:
# function, variable, snake case
def wash_hand():

boy = GoodBoy()