tags:

views:

434

answers:

6

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  A: 

You can break up lines like this:

if some_very_long_variable == SOME_VERY_LONG_CONST and \
   some_other_long_variable == SOME_OTHER_LONG_CONST:
  print "some very long string, that needs to be broken" \
        "into two lines"

When it comes to invoking functions, you don't even have to add '\', just call it like this:

  foo(very_long_arg1, very_long_arg2, very_long_arg3,
      very_long_arg4, very_long_arg5)

Take a look at some well formatted code (some open source python project) and learn from there. And read PEP 8

gruszczy
-1 for backlashes
Kimvais
Err.. why exactly? What's the problem?
gruszczy
They are evil (i.e. it's hard to see trailing spaces), better to use parenthesis.
Tomasz Zielinski
I have been using backslashes all my life and didn't even know, that one can use parenthesis. Thanks for advice.
gruszczy
+6  A: 

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'
}
Tor Valamo
+17  A: 

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 "1123456"

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.

Devin Jeanpierre
+1 for pointing out the whitespace problem.
mizipzor
**Please, use backlashes ONLY as a last resort** (see the link in my answer below)
Kimvais
'The difference is invisible-- there was a whitespace character in the second case.' ...after the backslash, that is. Just mentioning.
Boldewyn
@Kimvais: Isn't that exactly what Devin suggests here? He even shows an example error, that lead to this recommendation.
Boldewyn
@Boldewyn: Oops! It was tempting to think that the additional effort spent finding the error would reinforce the point, but, it is fixed.
Devin Jeanpierre
@Devin: It's just that when you look for whitespace errors in Python code you usually start *at the beginning of a line*. ;-)
Boldewyn
@Boldewyn, correct - so my comment is somewhat redundant. I would personally refactor the answer so that backlashes are explained only after the better solutions.
Kimvais
Who has an editor that doesn't remove trailing whitespace on saves?
Tor Valamo
A: 

pep8.py claims to be able to reformat your code to confirm to PEP 008 one of whose rules in that width of lines should not exceed 80 chars. Perhaps you can use this (assuming you've already written your code). Otherwise, the suggestions by the other folks who've answered are greatly beneficial.


Oops. Sorry. this just warns you. Forget this.

Noufal Ibrahim
A: 

Idiomatic Python says:

Use backslashes as a last resort

So, If using parentheses () is possible, avoid backlashes. If you have a a.train.wreck.that.spans.across.a.dozen.cars.and-multiple.lines.accross.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.

Kimvais
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.
Boldewyn
using `print("""...text...""")` or `print("text" "text" "text")`
Kimvais
+1  A: 

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!")

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

(d
 [42] = "H2G2")

because the parenthesis indicates the start of a ("calculated") expression, which cannot contain assignments (=). This problem can appear if d is written as a long expression, in which case you may want to do the assignment on the next line (e.g., if d is actually expressed as the long expression this_is_a_long_dict_name.setdefaults(this_is_a_long_key_for_the_dict, {}).

Another example is the following code, which generates a syntax error:

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

In these cases, one can either use the "\" syntax, or split the code over multiple statements.

EOL