Python: '#' Comments after backslash

MarcinKonowalczyk picture MarcinKonowalczyk · Jul 13, 2013 · Viewed 11.5k times · Source

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

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

Answer

Tadeck picture Tadeck · Jul 13, 2013

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