This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Sequences style guide

Style guide for sequences

face Josiah Wang

A few more style recommendations from PEP 8…

Trailing commas

You can optionally add commas to the end of a list or tuple (and function arguments). This is compulsory for tuples with only one element, i.e. (0,).

Training commas are usually redundant, but can be useful when you are expecting the list/tuple to be extended in the future. In this case, put each item in its own line, and have the closing bracket/parenthesis on a separate line.

# Recommended

config_files = [
    "options.cfg",
    "settings.txt",
    ]

initialize(config_files,
           error=True,
           )
# Not recommended

config_files = ["options.cfg", "settings.txt",]

initialize(config_files, error=True,)

No spaces between a trailing comma and a closing parenthesis

When you do use trailing commas (i.e. when it is a tuple with one element), omit the space between the trailing comma and the closing parenthesis.

# Recommended!
my_tuple = (0,)
# Not recommended!
my_tuple = (0, )

Aligning brackets

PEP 8 says that “the closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character of the last line of list … or it may be lined up under the first character of the line that starts the multiline construct”. Therefore, both the following (taken directly from PEP 8) are acceptable.

my_list = [
    1, 2, 3,
    4, 5, 6,
    ]

my_list = [
    1, 2, 3,
    4, 5, 6,
]