...

/

Indentation

Indentation

This lesson guides you how to indent code in Python.

Code Layout

Continuation lines should align wrapped elements either vertically using Python’s implicit line joining inside parentheses, brackets, and braces, or using a hanging indent. When using a hanging indent the following should be considered:

  1. There should be no arguments on the first line.
  2. Indentation should be used to clearly distinguish itself as a continuation line.

Aligned with Opening Delimiter

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

Add 4 Spaces

Press + to interact
# Add 4 spaces (an extra level of indentation) to distinguish arguments from the rest.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)

Hanging Indents

When there are many parameters:

Press + to interact
# Hanging indents should add a level.
foo = long_function_name(
var_one, var_two,
var_three, var_four)

Tabs or Spaces?

  • Spaces are the preferred indentation method.

  • Tabs should be used solely to remain consistent with code that is already indented with tabs.

  • Python 3 disallows mixing the use of tabs and spaces for indentation.

Maximum Line Length

  • There should be no more than 79 characters in a single line.
  • Try to avoid scrolling the widget horizontally.

Should a Line Break Before or After a Binary Operator?

No, operators sit far away from their operands.

Press + to interact
# Easy to match operators with operands
income = (x
+ y
- z)

Blank Lines

  • Top-level function and class definitions should follow two blank lines.

  • Method definitions inside a class are surrounded by a single blank line.

  • Extra blank lines may be used to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners.

  • Use blank lines in functions, sparingly, to indicate logical sections.

Imports

Imports should usually be on separate lines:

Press + to interact
import os
import sys

It’s okay to say this though:

Press + to interact
from subprocess import Popen, PIPE