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
result = some_function(
first_argument,
second_argument,
third_argument,
keyword_arg=value
)
result = some_function(first_argument,
second_argument,
third_argument)Conditional Statements
if (user.is_authenticated and
user.has_permission('edit') and
document.is_editable):
process_document(document)
if (
user.is_authenticated
and user.has_permission('edit')
and document.is_editable
):
process_document(document)Calculations and Expressions
total_price = (
base_price
+ shipping_cost
+ tax_amount
- discount
)
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
message = (
"This is a very long message that needs to be "
"split across multiple lines for better readability."
)
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"
)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.
"""
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:
result = (
df
.filter(items=['name', 'age', 'city'])
.dropna()
.sort_values(by='age')
.reset_index(drop=True)
)
cleaned_text = (
raw_text
.strip()
.lower()
.replace('\n', ' ')
.split()
)Dictionary and List Literals
Break after each item for better readability:
config = {
'database_host': 'localhost',
'database_port': 5432,
'database_name': 'myapp',
'debug_mode': True,
'log_level': 'INFO',
}
allowed_origins = [
'http://localhost:3000',
'https://example.com',
'https://api.example.com',
]The Backslash (Use Sparingly)
The backslash \ allows line continuation but is fragile: an invisible space after \ causes a syntax error.
total = first_value + \
second_value
total = (first_value +
second_value)Only use backslashes when parentheses aren't possible, such as with with statements in older Python versions:
with open('input.txt') as infile, \
open('output.txt', 'w') as outfile:
outfile.write(infile.read())
with (
open('input.txt') as infile,
open('output.txt', 'w') as outfile
):
outfile.write(infile.read())Import Statements
For multiple imports from one module:
from collections import (
Counter,
defaultdict,
namedtuple,
OrderedDict,
)
from os.path import exists, join, dirnameUsing Auto-Formatters
Modern Python projects should use automatic formatters to handle line breaks consistently:
Black
pip install black
black my_script.pyRuff
pip install ruff
ruff format my_script.pyBoth tools automatically break long lines following PEP 8 conventions, eliminating manual formatting decisions.
Method Comparison
| Method | Recommendation | Notes |
|---|---|---|
Parentheses () |
Preferred | Safe, readable, Pythonic |
| Implicit string joining | Preferred | Cleaner than + concatenation |
| Trailing commas | Recommended | Cleaner diffs, fewer errors |
Backslash \ |
Avoid | Fragile, error-prone |
| Auto-formatter | Essential | Eliminates 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.