I recently started learning Python, and as I am a bad student, I didn't follow the coding style PEP8 recommends. So I'm currently in the process of rewriting all of my code to follow PEP8, and that basically means breaking long lines. I ran into several cases where I didn't know how to break my line, and the Internet doesn't seem to be very helpful about this. But fortunately my awesome coworkers are, so here are some examples of cases I had to deal with, and how I ended up dealing with them.

Before I start showing examples, I just wanted to outline the few rules that matter here about PEP8:

  • Lines must not be longer than 79 characters ;
  • Use 4-space indentation for blocks ;
  • Alignment matters ;
  • The rest of the rules is well described in the PEP8 documentation.

Breaking an if statement

if condition1 and condition2 and condition3 and condition4 and condition5 or condition6:
    do_stuff()

At first I did something like this:

if condition1 and condition2 and condition3 and condition4 and condition5 or \
   condition6:
    do_stuff()

It seemed better to me mainly because that way the second line of conditions is not on the same indentation level than the content of the block, but my coworkers convinced me that using parentheses instead of backslashes is better. Reasons are backslashes are not "pythonic", and the use of parentheses shows the limits of the conditions.

Here is what I then thought would be the best solution:

if (condition1 and condition2 and condition3 and condition4 and condition5 or
    condition6):
    do_stuff()

But it's still not perfect as the block is aligned with conditions, and it makes it difficult to differenciate them. I believe now the best way to go is the following:

if (condition1 and 
    condition2 and 
    condition3 and 
    condition4 and 
    condition5 or
    condition6
):
    do_stuff()

Assert

assert condition, "This is a very long error message because I like to be verbose when I describe assertion errors with this content: %s" % variable

Becomes

assert condition, ("This is a very long error message because I like to be "
                   "verbose when I describe assertion errors with this "
                   "content: %s" % variable)

Or when the condition is long:

assert condition1 and condition2 and condition3 or condition4, (
    "This is a small error message. ")

Other examples?

If you ran into similar examples and couldn't find a documented solution on the Web, please share them in the comments and I'll add them here!