4

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?

ely
  • 74,674
  • 34
  • 147
  • 228
  • PEP 8 is cool with 100-character lines nowadays if your coworkers are okay with it :-) – roippi Mar 27 '14 at 02:32
  • 1
    I prefer 80. On a 24-inch monitor if I have a vertical split screen with two buffers in Emacs, 100 characters doesn't fit. But even if working on a project that does allow 100 this info might still be relevant. – ely Mar 27 '14 at 02:45
  • your last example looks cool to me, tupling the LHS, line-by-line comments. you can (it is syntactically correct to) put `,` even after the last one - `some_desc_name4,` and it becomes easier to extend if required – n611x007 Dec 12 '14 at 15:23

2 Answers2

5

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.
BoltzmannBrain
  • 5,082
  • 11
  • 46
  • 79
0

It would make sense that if a function returns a tuple, the values are all related and do not need individual commenting. That description would probably make more sense sitting within the function definition. Your first option would then be the best solution that quickly sets the function result to 4 different variables. Another option would be to simply use the entire tuple as a variable:

some_desc_name1 = some_descriptively_named_function()
print some_desc_name1[0] # Comment 1
ystan-
  • 1,474
  • 1
  • 19
  • 43