How can I make my Python code stay under 80 characters a line?

sahana picture sahana · Jan 15, 2010 · Viewed 47.1k times · Source

I have written some Python in which some lines exceed 80 characters in length, which is a threshold I need to stay under. How can I adapt my code to reduce line lengths?

Answer

Devin Jeanpierre picture Devin Jeanpierre · Jan 15, 2010

My current editor (Kate) has been configured to introduce a line break on word boundaries whenever the line length reaches or exceeds 80 characters. This makes it immediately obvious that I've overstepped the bounds. In addition, there is a red line marking the 80 character position, giving me advance warning of when the line is going to flow over. These let me plan logical lines that will fit on multiple physical lines.

As for how to actually fit them, there are several mechanisms. You can end the line with a \ , but this is error prone.

# works
print 4 + \
    2

# doesn't work
print 4 + \ 
    2

The difference? The difference is invisible-- there was a whitespace character after the backslash in the second case. Oops!

What should be done instead? Well, surround it in parentheses.

print (4 + 
    2)

No \ needed. This actually works universally, you will never ever need \ . Even for attribute access boundaries!

print (foo
    .bar())

For strings, you can add them explicitly, or implicitly using C-style joining.

# all of these do exactly the same thing
print ("123"
    "456")
print ("123" + 
    "456")
print "123456"

Finally, anything that will be in any form of bracket ((), []. {}), not just parentheses in particular, can have a line break placed anywhere. So, for example, you can use a list literal over multiple lines just fine, so long as elements are separated by a comma.

All this and more can be found in the official documentation for Python. Also, a quick note, PEP-8 specifies 79 characters as the limit, not 80-- if you have 80 characters, you are already over it.