Commenting with line continuation

1.2k views Asked by At

I have this block of code I want to comment but inline comments don't work. I'm not sure what PEP8 guideline applies here. Advice?

        if next_qi < qi + lcs_len \ # If the next qLCS overlaps 
        and next_ri < ri + lcs_len \ # If the next rLCS start overlaps 
        and next_ri + lcs_len > ri: # If the next rLCS end overlaps
            del candidate_lcs[qi] # Delete dupilicate LCS.
2

There are 2 answers

1
AudioBubble On BEST ANSWER

In Python, nothing can come after the \ line continuation character.

However, you can do what you want if you put your condition in parenthesis:

if (next_qi < qi + lcs_len   # If the next qLCS overlaps 
and next_ri < ri + lcs_len   # If the next rLCS start overlaps 
and next_ri + lcs_len > ri): # If the next rLCS end overlaps
    del candidate_lcs[qi] # Delete dupilicate LCS.

Below is a demonstration:

>>> if (1 == 1   # cond 1
... and 2 == 2   # cond 2
... and 3 == 3): # cond 3
...     print True
...
True
>>>

The relevant PEP 8 guideline is:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

0
Ned Batchelder On

An often overlooked way to deal with very long lines is to break them into more, shorter lines:

q_overlaps = next_qi < qi + lcs_len          # If the next qLCS overlaps 
r_start_overlaps = next_ri < ri + lcs_len    # If the next rLCS start overlaps 
r_end_overlaps = next_ri + lcs_len > ri      # If the next rLCS end overlaps
if q_overlaps and r_start_overlaps and r_end_overlaps:
    del candidate_lcs[qi] # Delete dupilicate LCS.