Explain Codes LogoExplain Codes Logo

How can I do a line break (line continuation) in Python?

python
line-continuation
python-best-practices
code-readability
Anton ShumikhinbyAnton Shumikhin·Jan 8, 2025
TLDR

Line continuation in Python is accomplished with a backslash (\) signifying a line continuation:

sentence = "This is an example of " \ "a line continuation."

Alternatively, leverage parentheses (()) or brackets ([]) to achieve implicit line continuation:

values = ( 10, 20, 30, 40, 50, 60 )

These methods promote readability and align with PEP 8 recommendations.

Deep dive into Python's line continuation

Implicit beats explicit

When dealing with multi-line expressions, it's often more readable to use parentheses for implicit line continuation:

long_sum = ( first_operand + # Here's the first part of your sum second_operand + # Second verse, same as the first third_operand # Last but not least! )

This approach avoids the risk of a syntax error when an inadvertent whitespace is left after the backslash (\).

Handle backslashes with care

While a backslash (\) gives you an explicit way to split a line, ensure there is no whitespace after it:

print("Don't forget to add milk, " \ "eggs, and python to the grocery list!") # Wait, python? 😂

Although valid, this explicit method is less popular due to its susceptibility to bugs caused by an extra whitespace and readability issues.

Math to the rescue

Breaking lines before binary operators in line with traditional mathematical conventions (thanks Knuth!) enhances clarity. Remember, clear > clever in the programming world:

subtotal = (price * quantity # First we multiply... + tax) # ...then we add the tax! Easy as pie, but not as tasty

Don't break the code

It's crucial to ensure line continuation doesn't disrupt the intended functionality of your code.

Strategies for edge cases and maintaining style guide alignment

Smooth operator

Aim for consistency, particularly around operators in line continuation, to uphold local readability:

# Back, and to the left... just like PEP 8 suggests result = (var_one + var_two - var_three) # arithmetic... now with more suspense!

When in Rome

While PEP 8 is great, remember to follow the local coding style for operator placement if it deviates for reasons like backward compatibility or team preference.

Run away from backslashes

Avoid unnecessary backslashes. Opt for implicit line continuation methods with parentheses, brackets, or curly braces:

# Cleverly disguised as an array elements = ["Hydrogen", "Helium", "Lithium", "Beryllium"] # Shoutout to the periodic table! # Not so clever elements = "Hydrogen", "Helium", \ "Lithium", "Beryllium" # I couldn't fit all 118. Sorry, Mendeleev