High readability is one of the great things about Python. For example, it forces the programmer to keep correct indentation, making the code automatically readable and not including unnecessary "end" statements.
However, high readability comes not only from the syntax of the language itself, but also from its community and guidelines.
PEP8 guideline with better readability than the python.org one: https://pep8.org/
def make_complex(*args):
x, y = args
return dict(**locals())
def make_complex(x, y):
return {'x': x, 'y': y}
Example #2
import requests
r = requests.get("https://miguelgfierro.com")
from requests import *
r = get("https://miguelgfierro.com")
Example #3
def read(filename):
if filename[-4:] == '.csv':
# code for reading a csv
pass
elif filename[-5:] == '.json':
# code for reading a json
pass
def read_csv(filename):
pass
# code for reading a csv
def read_json(filename):
pass
# code for reading a json
Explicit examples make it clear right away what is happening even if in some cases this leads to redundant information.
Implicit examples assume additional knowledge. This assumption may be correct. It may be incorrect.
It is often easier to write implicit code. When you write code, you have the additional knowledge. When you read code, this may not be the case. This leads to cases when while writing code you compare Implicit and Explicit examples from the perspective of someone with additional knowledge. From this perspective explicit code is redundant.
You reasoning shouldn't be "what is easier to write". It should be "what is easier to read assuming minimal pre-existing knowledge about how the program works". In this case explicit code is much more often the better option.
"Sparse is better than dense"
It may be fun to put everything into a single dense statement. However, it hurts readability.
Splitting code into small simple parts lets the reader easily understand what each part does separately.
print 'one'; print 'two'
if x == 1: print 'one'
if <complex comparison> and <other complex comparison>:
# do something
print 'one'
print 'two'
if x == 1:
print 'one'
cond1 = <complex comparison>
cond2 = <other complex comparison>
if cond1 and cond2:
# do something
# A single statement that is very hard to understand.
print('\n'.join("%i bytes = %i bits which has %i possible values." % (j, j*8, 256**j-1) for j in (1 << i for i in range(8))))
Example from Homework 1. Problem #18
A = int(input())
B = int(input())
print(((((A // B) * A) + ((B // A) * B)) // ((A // B) + (B // A))))
a = int(input())
b = int(input())
remainder_a = a // b
remainder_b = b // a
max_number = (remainder_a * a + remainder_b * b) // (remainder_a + remainder_b)
print(max_number)
Use four spaces per indentation level.
You can start a next line inside parentheses, brackets and braces. In this case you are technically free to use any indentation you want. So you should make readability your priority when choosing the indentation.
# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# More indentation included to distinguish this from the rest.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)
# Arguments on first line forbidden when not using vertical alignment.
foo = long_function_name(var_one, var_two,
var_three, var_four)
# Further indentation required as indentation is not distinguishable.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
Use whitespace
hypot2 = x*x + y*y
Avoid whitespace
spam(ham[1], {eggs: 2})
spam(1)
and spam_list[1]
)print(a, b, sep='')
)Recommended maximum line length is 79 symbols (and the newline symbol, making the total 80).
Why?
The preferred way of wrapping long lines is by using Python’s implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses.
Backslashes may be appropriate in some cases where the preferred way specifically fails. If you have a free choice of method, use parentheses.
The preferred way of naming variables and functions in Python is lower_case_with_underscores
.
Use descriptive names. Make code self-documenting, so that anyone would be able to understand what happens right away.
# Init a & b to 0
a=0
b=0
# Read a & b
a,b = readvalues()
# Add a and b, and divide by 2
c=a+b
#Divide c by 2
d = c / 2
# print c
print(c)
number1 = 0
number2 = 0
number1, number2 = readvalues()
sum = number1 + number2
average = sum / 2
print(average)
Use comments to help understand reasoning behind the code.
# Our code doesn't work correctly when using a usb, so we have to add this extra checks
if (special_case_usb):
Do_something_special