Is there a way to put comments in multiline code?

PythonCommentsFormatMultilineBackslash

Python Problem Overview


This doesn't work:

something = \
    line_of_code * \    #  Comment
    another_line_of_code * \    #  Comment
    and_another_one * \         #  Comment
    etc

Neither does this:

something = \
    #  Comment \
    line_of_code * \
    #  Comment \
    another_line_of_code * ...

Neither does this:

something = \
    ''' Comment ''' \
    line_of_code * \
    ''' Comment ''' \
    another_line_of_code * ...

Is there a way to make comments in the code broken into multiple lines?

Python Solutions


Solution 1 - Python

Do it like that:

a, b, c, d = range(1, 5)
 
result = (
    # First is 1
    a *
    # Then goes 2, result is 2 now
    b *
    # And then 3, result is 6
    c *
    # And 4, result should be 24
    d
)

Actually, according to PEP8 parentheses are preferred over slashes, when breaking something into multiple lines:

> 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.

In your case it also allows to put comments.

Here is a proof, that it works: http://ideone.com/FlccUJ

Solution 2 - Python

Not sure what you are trying to do is supported by python. Read PEP8 section about inline comments. Putting comments in the middle of line continuations is "ugly" and probably confusing.

Python way is with # on every line if you want to comments something or for inline comments everything after # is ignored.

If you really want to comment a multiline statement that is really necessary put it before or after it.

a, b, c, d = range(1, 5)
# a is ..., b is ...
# c is ..., d is ...
result = (a, b, c, d)

definately don't want to get into an argument about style, but just because you can do something doesn't mean that it is clear. Inline comments are great for clarifyling short lines of code that just need a short pointer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcinKonowalczykView Question on Stackoverflow
Solution 1 - PythonTadeckView Answer on Stackoverflow
Solution 2 - PythonJoopView Answer on Stackoverflow