ruk·si

🐍 Python
Code Layout

Updated at 2017-01-03 01:22

Use 4 space indention for consistency. Most widely used indention standard. Never mix tabs and spaces.

def long_function_name(parameter_one):
....print(var_one)

Limit lines to 80 characters. More in master coding guide.

Limit one statement per line. You should find no need to use semicolons.

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

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

Variable definition can go multiline. Multiline variable construct continuation should be indented and the closing symbol should go to a new line.

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

Function definition can go multiline. Function definition continuation lines should be indented 8 spaces to distinguish it from the function body. Losing parenthesis should be placed after the last parameter. Align parameters with the first parameters.

# bad
def long_function_name(
    var_one, var_two, var_three,
    var_four) -> None:
    print(var_one)

# good
def long_function_name(var_one,
                       var_two,
                       var_three,
                       var_four) -> None:
    print(var_one)

Avoid backslashes \ to continue lines. Use only if structure does not allow line breaks. Backslash continuation indention is 8 spaces.

# acceptable
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())
    file_1.close()
    file_2.close()

Use blank lines to group related groups of function calls and variables. Use blank lines sparingly and mind the vertical space.

Prefer aligning code to the left. Reformatting code after change is annoying. Maybe used in a few places like configuration files.

# bad
x: int             = 1
y: int             = 2
long_variable: int = 3

# good
x: int = 1
y: int = 2
long_variable: int = 3

Use spaces. Surround following operators with a single space on either side: =, +=, -=, ==, <, >, !=, <>, <=, >=, in, not in, is, is not, and, or, not. Consider removing space to show highest priority operator.

# bad
i=i+1
submitted +=1
x = x * 2 - 1
hypot2 = x * x + y * y
c = (a + b) * (a - b)

# good
i = i + 1
submitted += 1
x = x*2 - 1
hypot2 = x*x + y*y
c = (a+b) * (a-b)

No spaces around keyword argument or default parameter assignment. Except add spaces if type is defined.

# bad
def complex(real, imag = 0.0, name: str='John'):
    return magic(r = real, i = imag)

# good
def complex(real, imag=0.0, name: str = 'John'):
    return magic(r=real, i=imag)

Sources