'Is it possible to add comments on each line of a split up parallel assignment in Python? [duplicate]

I have the following scenario: I have a function which returns multiple values:

def func(x):
     return x+1, x+2, x+3, x+4

I'd like to do the following:

a, # this is the x+1 value
b, # this is the x+2 value
c, # this is the x+3 value
d = func(7) # and this is the x+4 one!

i.e. I want the simple assignment

a, b, c, d = func(7)

but with comments in between describing each variable.

The function I have is obviously more complex than this, and so I'd like to include many details about each variable (1-2 sentences) that is output. Is there a way to do this? I tried adding a \ character before the # on each line as well as after the comment on each line, but neither work

In my experience, one can call a function with multiple parameters, and do this sort of multi line commenting (without any need for \ characters)



Solution 1:[1]

Use parentheses:

(
    a,  # some facts
        # some more
    b,  # look at me!
    c,
    d,  # I like to say stuff
        # I should just write doctrings
) = func(42)

But really, you should just be documenting this in a docstring for your function. Any text-editor/IDE will surface that information at your fingertips.

Note, according to PEP 8, the official style-guide:

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.

Solution 2:[2]

Simply use parenthesis

>>> (
...     a, # One
...     b, # Two
...     c, # Three
...     d  # Four
... ) = func(7)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juanpa.arrivillaga
Solution 2 Vishnudev