Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different number of return values in Python function

Tags:

python

Is it okay/good practice to return different number of return values from a function in Python? If yes, how should the caller handle the return values? e.g.

def func():
    if(condition_1):
        return 1,2
    if(condition_2):
        return 1
    if(condition_3):
        return 1,2,3,4

Note: condition_1,condition_2 and condition_3 are local to the function func so the caller has no idea how many values will be returned.

like image 307
Suresh Kumar Avatar asked Jun 08 '15 07:06

Suresh Kumar


People also ask

Can a function have multiple return values in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

How many returns can a function have Python?

Python doesn't return values, it returns objects. To that end, a function can only return one object. That object can contain multiple values, or even refer to other objects, so while your function can pass back multiple values to the caller, it must do so inside of a single object.

What is the different return value of a Python function?

A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.

Can a function have multiple return values?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.


1 Answers

Is it pythonic for a function to return multiple values? have a great explanation in this.

But in your case, it depends on your use-case. If you know how to handle returning data, then there is no problem in using this. Like:

def func():
    if(condition_1):
        return a,b
    if(condition_2):
        return (a, )
    if(condition_3):
        return c,d,e,f
    if(condition_4):
        return a,b

vals = func()
if len(vals) == 2:
    # We are sure that we will get `a,b` in return
    do something ...
elif len(vals) == 3:
    ...

In example above, function that will process vals tuple knows how to handle returning data according to some criteria. It have 2 return possibilities that returns the same data!

If you know exactly how to handle data, then it is ok to go with different number of returns. The key point in here is functions do a single job. If your have problems in recognizing the return values, then your function is doing more than one job or you must avoid using different number of arguments.

like image 59
FallenAngel Avatar answered Nov 15 '22 20:11

FallenAngel