Can I assign the result of a function on multiple lines? Python

Question:

Lets say I have a function that return a lot of variables:

def func():
   return var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i,

Using this function results in very long lines

var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i = func()

Ideally, I would like to use the line breaker , e.g.

a = var 
    + var 
    + var 
    + var 
    + var

However, I don’t think this is possible with the result of a function (i.e. unpacking tuple). Are there methods to do so? Or should I find another way to return fewer variables? Do you have any other style suggestions?

Asked By: HerChip

||

Answers:

You can wrap the variables in round brackets

(var_a,
 var_b,
 var_c,
 var_d,
 var_e,
 var_f,
 var_g,
 var_h,
 var_i) = func()
Answered By: Guy

if you want you can accept the output of the function as a tuple

ans = func()

I don’t know what exactly is this value,
but you could consider using a data class to use the returned value, making it easier to access the data

class data():
    def __init__(self,var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i):
        self.var_a = var_a
        self.var_b = var_b
        self.var_c = var_c
        self.var_d = var_d
        self.var_e = var_e
        self.var_f = var_f
        self.var_g = var_g
        self.var_h = var_h
        self.var_i = var_i

def func():
    return data(var_a, var_b, var_c, var_d, var_e, var_f, var_g, var_h, var_i)

a=func()
print(a.var_a)
Answered By: Ohad Sharet

Just complementing, you can also work with multiple elements and use it to ignore some of them:

*ignore, i = func() # Ignore all elements except the last one
a, *ignore = func() # Ignore all elements except the first one
a, *ignore, i = func() # Ignore all elements except the first and last one
Answered By: Alex Rintt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.