How can I make my Python code stay under 80 characters a line? [closed]
Asked Answered
C

4

60

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?

Cookson answered 15/1, 2010 at 10:4 Comment(13)
Keeping code under 80 columns is something that should have died a decade ago. Targetting 80x25 terminals is absurd and leads to hideous code.Unimposing
@Glenn Maynard: I strongly disagree. Most people still use 80 character wide editor windows as there usually is more than one window you want to keep visible.Subsidy
Do what you like, but I'm certainly not defacing my code to support people who insist on editing code in tiny windows. Devin's answer shows just how hideous and unnatural code gets when you do this. A sensible limit is around 120 columns.Unimposing
Actually, I believe my example showed how hideous and unnatural code gets when you apply a 14-column limit. My answer would have been the same if the question had been about a 120-character limit, with those same "hideous" examples, so I'm not very convinced by your argument. Personally I care very little about this. If I set any maximum length, some lines inevitably will have to be shortened/split. Making the max smaller is reasonably OK within some margin, and 80/120 seem to be within the margin. And 80 is the status quo, so that's what I do. The code quality doesn't really suffer.Ananias
@Glenn Maynard : That was probably the most unpythonic comment I have heard for ages; "I'm certainly not making my code look less pretty for me to make it more readable for others"Subsidy
Call me crazy, but I like to be able to see the differences between versions when I'm using TortoiseMerge.Gwenny
@sahana: Note that the recommended (PEP 8) limit if 79 characters per line (not 80): lines of 80+ characters are generally too long.Revoice
I don't even fullscreen Visual Studio, and I don't restrict myself to 80 characters. Who still does this?Selftaught
From my experience making python code stay under 80 characters makes it much less readable. (I would suggest something around 160 characters)Pebrook
In the book 'Clean Code' by Robert C. Martin there are some good sections talking about the topic. In concrete, the author (personally) prefer a max limit of 120 characters but also gives a good criterion for choosing the length: "... you should never have to scroll to the right ...". In my case, I'm a Python developer and for the good of every developer (including me) I follow the standard, it means PEP8 and not more than 79 characters; what, in fact, meets the criterion.Tabasco
I also think 80 characters is way too little and causes more readability problems than it solves. I think 100-120 is a more sensible limit.Mercorr
limiting line length is not for the sake your screen not wide enough to show it, but for easy openning two editor window side by sideJinn
Just for the record I'm considering moving my current project to 150 chars per line. I'm sick of having to write my code differently to make it fit on 120. I've just done the SO search again to review the reasons for keeping it shorter and I can't find any. It's sub-optimal and awkward and contrary to a popular answer that says there's no obvious benefit from exceeding 80 chars I find the reverse in several ways: There are obvious problems with keeping to 80 chars, obvious benefits to increasing it and no obvious real problems with increasing it. And yes I do use long semantic variable names.Methodology
A
63

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.

Ananias answered 15/1, 2010 at 10:14 Comment(8)
Please, use backlashes ONLY as a last resort (see the link in my answer below)Subsidy
'The difference is invisible-- there was a whitespace character in the second case.' ...after the backslash, that is. Just mentioning.Babe
@Kimvais: Isn't that exactly what Devin suggests here? He even shows an example error, that lead to this recommendation.Babe
@Boldewyn: Oops! It was tempting to think that the additional effort spent finding the error would reinforce the point, but, it is fixed.Ananias
@Devin: It's just that when you look for whitespace errors in Python code you usually start at the beginning of a line. ;-)Babe
@Boldewyn, correct - so my comment is somewhat redundant. I would personally refactor the answer so that backlashes are explained only after the better solutions.Subsidy
Who has an editor that doesn't remove trailing whitespace on saves?Altricial
Parentheses do not "work universally". For example, they do not work around an assignment ((very_long_var_name = … <newline> …)), or in statements like (with open('very long file name') <newline> as …):. In fact, they only work with expressions (not statements), i.e. things that are "calculated" and return a value.Revoice
A
23

If the code exceeding 80 chars is a function call (or definition), break the argument line. Python will recognise the parenthesis, and sees that as one line.

function(arg, arg, arg, arg,
         arg, arg, arg...)

If the code exceeding 80 chars is a line of code that isn't naturally breakable, you can use the backslash \ to "escape" the newline.

some.weird.namespace.thing.that.is.long = ','.join(strings) + \
                                          'another string'

You can also use the parenthesis to your advantage.

some.weird.namespace.thing.that.is.long = (','.join(strings) +
                                           'another string')

All types of set brackets {} (dict/set), [] (list), () (tuples) can be broken across several lines without problems. This allows for nicer formatting.

mydict = {
    'key': 'value',
    'yes': 'no'
}
Altricial answered 15/1, 2010 at 10:9 Comment(1)
why not? thing = some.weird.namespace.thing.that, thing.long = ','.join(strings) + 'another string'Vermillion
R
23

I would add two points to the previous answers:

Strings can be automatically concatenated, which is very convenient:

this_is_a_long_string = ("lkjlkj lkj lkj mlkj mlkj mlkj mlkj mlkj mlkj "
                         "rest of the string: no string addition is necessary!"
                         " You can do it many times!")

Note that this is efficient: this does not result in string concatenations calculated when the code is run: instead, this is directly considered as a single long string literal, so it is efficient.

A little caveat related to Devin's answer: the "parenthesis" syntax actually does not "work universally". For instance, d[42] = "H22G" cannot be written as

(d
 [42] = "H2G2")

Parentheses can be used around "calculated" expression (which does not include an assignment (=) like above).

Another example was the following code, which used to generate a syntax error (at some point before Python 3.9):

with (open("..... very long file name .....")
      as input_file):

In fact, parentheses cannot be put around any statement, more generally (only expressions).

In these cases, one can either use the "" syntax, or, better (since "" is to be avoided if possible), split the code over multiple statements.

Revoice answered 15/1, 2010 at 13:4 Comment(1)
The with (open(... statement doesn't generate a syntax error for me (Python 3.9)Trophozoite
S
19

Idiomatic Python says:

Use backslashes as a last resort

So, if using parentheses () is possible, avoid backslashes. If you have a a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.across.the.whole.trainyard.and.several.states() do something like:

lines = a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines
lines.across.the.whole.trainyard.and.several.states()

Or, preferably, refactor your code. Please.

Subsidy answered 15/1, 2010 at 10:23 Comment(3)
If you need to print, say, a large amount of static text, a usage instruction for a CLI script for example, I'd like to see how you 'refactor' it.Babe
using print("""...text...""") or print("text" "text" "text")Subsidy
python3.6 f-string print(f'{text:-^80}') or print('{:-^80}'.format(text))Vermillion

© 2022 - 2024 — McMap. All rights reserved.