Mark Colan Mark Colan - 10 months ago 31
Python Question

statement spilling over more than one line

PEP8 tells me that the maximum line length should be 79. This sounds a bit like punched cards, and I'm used to longer lines, but as I learn Python, I'm trying to conform to the standard style.

Consider this line:

partsList[r][newPurchaseNotes] += partsList[r+1][newPurchaseNotes]

When indented 4 stops (using 4-space tabs per PEP8), it overflows. (If I use PEP8 underscore separators rather than Java-style mixed case, it's worse.)

If I break it into two lines like this:

+= partsList[r+1][newPurchaseNotes] is a syntax error (unexpected indent). Breaking it like this:

partsList[r][newPurchaseNotes] +=
partsList[r+1][newPurchaseNotes] is ALSO a syntax error (invalid syntax).

Here are two obvious solutions, neither of which I like:

  • use shorter names for variables

  • break the one statement into two with intermediate variables:

    s = partsList[r+1][newPurchaseNotes]
    partsList[r][newPurchaseNotes] += s

In researching this forum, I did find suggestions for reducing indentation levels for loops and for conditionals. In my case, I had if nested in if nested in a while inside a function. I changed the logic to reduce one level of if statements, but it was not enough to keep the line in 79 characters.


Python doesn't use semi-colons to denote the end of lines. Use a backslash to indicate the line is continued on the next line:

partsList[r][newPurchaseNotes] \
    += partsList[r+1][newPurchaseNotes]

The other way you can break a statement over multiple lines in python, is if the break happens within parentheses or brackets. In your example here, you could break the line between [ and ], but that would be really ugly.

One possibility is:

partsList[r][newPurchaseNotes] = (
    partsList[r][newPurchaseNotes] +

I'm not sure that that's an improvement though.