Tip 6 Wrap Long Lines

Pythonic Programming — by Dmitry Zinoviev (14 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Keep Letter Case Consistent | TOC | Self-Document Your Code 👉

★2.7, 3.4+ Python is known as a language of one-liners: statements that consist of only one line. That line, for sure, may be quite long. A long line does not fit your IDE or text editor’s window and is hard to read. If you have to use a long line statement, break it into several lines. Python treats a single backslash “\” at the very end of a line as a continuation symbol — it is ignored, and the line break that follows it is ignored too.

The best place to break a line is before an operator (for example, arithmetic, Boolean or comparison operator, or the “dot” (“.”) operator. Try to align the first operator on the continuation line with a similar operator on the previous line. These are “good” continuations that improve the readability of your code:

​ 1 + 2 + 3 + 4 \
​ + 5 + 6
​ s.lower().strip() \
​ .split()

This is a “bad” continuation that makes your code harder to read:

​ dir( \
​ )

Note that if you typed an opening bracket (“[”, “(”, or “{”) that has not been closed yet, there is no need for the continuation symbol: Python will patiently wait until you restore the balance:

​ dir( ​# This is legal, but do not do it, anyway!​
​ )

Unlike C/Java, Python allows breaking a line even within a single- or double-quoted…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.