问题
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?
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/22677078/python-style-for-line-length-and-format-when-unpacking-many-return-values