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:
- There should be no arguments on the first line.
- Indentation should be used to clearly distinguish itself as a continuation line.
Aligned with Opening Delimiter
# Aligned with opening delimiter.foo = long_function_name(var_one, var_two,var_three, var_four)
Add 4 Spaces
# 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:
# 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.
# Easy to match operators with operandsincome = (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:
import osimport sys
It’s okay to say this though:
from subprocess import Popen, PIPE