4

In Python, I want to do something like this

an_explicit_variable_name, another_explicit_variable_name, an_even_more_explicit_variable_name = function(foo)

But I also want this to be readable and fit on several short lines rather than one very long line. I didn't find any help in PEP 08. This question is somwhat related, but the answers aren't quite what I want.


This is the best I could come up with as far as line-length is concerned, but I don't really like using a[0] etc.

a = function(foo)
an_explicit_variable_name = a[0]
another_explicit_variable_name = a[1]
an_even_more_explicit_variable_name = a[2]

This doesn't work because the second line is still too long

_ = function(foo)
an_explicit_variable_name, another_explicit_variable_name, an_even_more_explicit_variable_name = _

Should I separate the variables I am declaring over several lines? If so, how do I indent?

an_explicit_variable_name, \
    another_explicit_variable_name, \
    an_even_more_explicit_variable_name \
    = function(foo)


an_explicit_variable_name, \
        another_explicit_variable_name, \
        an_even_more_explicit_variable_name \
    = function(foo)

What would be the proper style to adopt in this situation?

Community
  • 1
  • 1
usernumber
  • 1,958
  • 1
  • 21
  • 58

1 Answers1

13

Just use parentheses:

(an_explicit_variable_name, 
 another_explicit_variable_name, 
 an_even_more_explicit_variable_name) = function(foo)

Alternatively, if the data belongs together, create a container object to hold it together, e.g. a collections.namedtuple, then do:

data = container(*function(foo))
# use e.g. data.an_explicit_variable_name
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437