1.11. Formatting Code#

When a statement is too long, you can split it across multiple lines in two ways:

  1. Preferred: Use implicit line continuation inside parentheses (), brackets [], or braces {}. No backslash needed.

  2. Discouraged: Use the explicit line-continuation character \.

1.11.1. Example 1: Using parentheses (preferred)#

(2 +
 3)

1.11.2. Example 2: Using the line-continuation character (discouraged)#

2 + \
3

1.11.3. Additional examples#

1.11.3.1. Single line (hard to read)#

result = 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

1.11.3.2. With implicit line continuation using parentheses (readable)#

result = (
    2 + 3 + 4 +
    5 + 6 + 7 +
    8 + 9 + 10
)

Tips:

  • Align wrapped lines for clarity.

  • Prefer breaking after an operator.

  • For lists, dicts, and function calls with many arguments, wrap and indent similarly:

numbers = [
    2, 3, 4, 5, 6, 7, 8, 9, 10,
]

config = {
    "host": "localhost",
    "port": 5432,
    "use_ssl": True,
}

total = sum(
    x
    for x in range(1, 11)
)