Skip to main content

How to Break Long Lines in Python

PEP 8 recommends a maximum line length of 79 characters, though many modern teams use 88 (Black's default) or 100. Breaking lines correctly keeps code readable and maintainable.

This guide covers the standard techniques for splitting long lines while following Python best practices.

Using Implicit Continuation (Parentheses)

The preferred method is wrapping expressions in parentheses. Python allows natural line breaks inside (), [], and {}.

Function Calls

# Long function call - use parentheses for clean breaks
result = some_function(
first_argument,
second_argument,
third_argument,
keyword_arg=value
)

# Or align with opening parenthesis
result = some_function(first_argument,
second_argument,
third_argument)

Conditional Statements

# Wrap conditions in parentheses
if (user.is_authenticated and
user.has_permission('edit') and
document.is_editable):
process_document(document)

# Alternative: one condition per line
if (
user.is_authenticated
and user.has_permission('edit')
and document.is_editable
):
process_document(document)
Operator Placement

PEP 8 recommends breaking before binary operators (and, or, +) for better readability:

# Preferred - operator at start of new line
total = (first_value
+ second_value
+ third_value)

Calculations and Expressions

# Mathematical expressions
total_price = (
base_price
+ shipping_cost
+ tax_amount
- discount
)

# List comprehensions
filtered_items = [
item.process()
for item in long_list_of_items
if item.is_valid() and item.meets_criteria()
]

Breaking Long Strings

Do not use + to concatenate static strings. Python automatically joins adjacent string literals inside parentheses.

Implicit String Concatenation

# Python joins these automatically (no + needed)
message = (
"This is a very long message that needs to be "
"split across multiple lines for better readability."
)

# SQL queries
query = (
"SELECT users.id, users.name, orders.total "
"FROM users "
"INNER JOIN orders ON users.id = orders.user_id "
"WHERE orders.status = 'pending' "
"ORDER BY orders.created_at DESC"
)
Don't Forget Trailing Spaces

When splitting strings, remember to include spaces at the end of each line segment, or the words will run together.

Multi-line Strings with Triple Quotes

For text blocks where whitespace matters less:

description = """
This is a multi-line string that preserves
all whitespace and newlines exactly as written.
Useful for documentation or templates.
"""

# Use textwrap.dedent for indented code
from textwrap import dedent

html = dedent("""
<html>
<body>
<p>Hello, World!</p>
</body>
</html>
""").strip()

Method Chaining

For chained method calls, break after each method:

# Pandas example
result = (
df
.filter(items=['name', 'age', 'city'])
.dropna()
.sort_values(by='age')
.reset_index(drop=True)
)

# String methods
cleaned_text = (
raw_text
.strip()
.lower()
.replace('\n', ' ')
.split()
)

Dictionary and List Literals

Break after each item for better readability:

# Dictionary
config = {
'database_host': 'localhost',
'database_port': 5432,
'database_name': 'myapp',
'debug_mode': True,
'log_level': 'INFO',
}

# List
allowed_origins = [
'http://localhost:3000',
'https://example.com',
'https://api.example.com',
]
Trailing Commas

Always add a trailing comma after the last item. This makes diffs cleaner when adding new items and prevents syntax errors.

The Backslash (Use Sparingly)

The backslash \ allows line continuation but is fragile: an invisible space after \ causes a syntax error.

# Avoid this - fragile
total = first_value + \
second_value

# Prefer this - safer
total = (first_value +
second_value)

Only use backslashes when parentheses aren't possible, such as with with statements in older Python versions:

# Python 3.9 and earlier (3.10+ allows parentheses)
with open('input.txt') as infile, \
open('output.txt', 'w') as outfile:
outfile.write(infile.read())

# Python 3.10+ preferred
with (
open('input.txt') as infile,
open('output.txt', 'w') as outfile
):
outfile.write(infile.read())

Import Statements

For multiple imports from one module:

# Use parentheses for multiple imports
from collections import (
Counter,
defaultdict,
namedtuple,
OrderedDict,
)

# Or keep short import lists on one line
from os.path import exists, join, dirname

Using Auto-Formatters

Modern Python projects should use automatic formatters to handle line breaks consistently:

Black

pip install black
black my_script.py

Ruff

pip install ruff
ruff format my_script.py

Both tools automatically break long lines following PEP 8 conventions, eliminating manual formatting decisions.

Method Comparison

MethodRecommendationNotes
Parentheses ()PreferredSafe, readable, Pythonic
Implicit string joiningPreferredCleaner than + concatenation
Trailing commasRecommendedCleaner diffs, fewer errors
Backslash \AvoidFragile, error-prone
Auto-formatterEssentialEliminates manual formatting

Summary

  • Wrap long expressions in parentheses for natural line breaks.
  • Use implicit string concatenation instead of + for static strings.
  • Break before operators for better readability.
  • Add trailing commas in multi-line collections.
  • Avoid backslashes since they're fragile and error-prone.
  • Use Black or Ruff to automate formatting entirely.