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?
问题:
回答1:
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.
回答2:
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'
}
回答3:
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.
回答4:
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")
because parentheses can only be used around "calculated" expression (this does not include an assignment (=) like above).
Another example is the following code, which generates a syntax error:
with (open("..... very long file name .....")
as input_file):
In fact, parentheses cannot be put around statements, 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.