Search code examples
pythonpep8iterable-unpackingargument-unpacking

Python style for line length and format when unpacking many return values


Suppose that function some_descriptively_named_function returns a 4-tuple of 4 return parameters. I want to call some_descriptively_named_function, adhere to the 80-character line length limit, and unpack all 4 outputs each into a descriptively-named variable:

some_desc_name1, some_desc_name2, some_desc_name3, some_desc_name4 = some_descriptively_named_function() 

One option is:

some_desc_name1, some_desc_name2, some_desc_name3, some_desc_name4 = (
    some_descriptively_named_function()
)

With four unpacked values, though, even this can be pushing it for line length. And if I wanted to make a brief comment on each argument, it's not easy to lay it out nicely.

The following works but it's unclear if this is considered good or very bad.

(some_desc_name1, # Comment 1
 some_desc_name2, # Comment 3
 some_desc_name3, # Comment 3
 some_desc_name4  # Comment 4
) = some_descriptively_named_function()

It's certainly good for line length, but it's weird trying to think of how PEP8 might apply to the parentheses happening right at the beginning of a line.

Is there an established (hopefully PEP8 related) Python style guideline for this?


Solution

  • Your format LGTM, but a couple suggestions:

    (some_desc_name1,
     some_desc_name2,
     some_desc_name3,
     some_desc_name4) = some_descriptively_named_function()
    
    • Make the calling function more clear by pulling it out
    • Don't comment the unpacked variables. The docstring for some_descriptively_named_function() should define these clearly.