There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8 and allow you to make better use of your space. They are:
msg = (
'This message is so long, that it requires '
'more than {x} lines.{sep}'
'and you may want to add more.').format(
x=x, sep=2*'\n')
print(msg)
Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered).
The advantages are same with what is described below, the difference is that you can do it anywhere.
Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msg
clearly (compare with msg +=
one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a +
on one random line ?).
Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.
A close alternative is:
msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)
Though the first is preferable.
The other approach is like the previous ones, though it starts the message on the line below the print
.
The reason for this is to gain space on the left, otherwise the print(
itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of print
above them. So if your message was already long, this way it's forced to be spread over even more lines.
Contrast:
raise TypeError('aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa')
with this (suggested here):
raise TypeError(
'aaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaa')
The line spread was reduced. Of course this last approach does no apply so much to print
, because it is a short call. But it does apply to exceptions.
A variation you can have is:
raise TypeError((
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaa {x} aaaaa').format(x=x))
Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.