Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a function optionally return one or more values

Tags:

python

return

What is the preferred way to ignore an optional return values of function f()?

a)

foo, _ = f()

b)

foo = f()[0]

c)

def f(return_bar=True):
    if return_bar:
        return foo, bar
    else:
        return foo

foo = f(return_bar=False)
like image 668
Max Avatar asked May 26 '26 07:05

Max


1 Answers

You're setting yourself up for trouble if your function returns two variables sometimes and one variable another time.

foo, _ = f()

Usually using underscore to ignore variables is the standard practice, but in your case, if for whatever reason, this call to f() returned only one variable, you will get a runtime error.

Unless you can guarantee that f() will return two variables this time, it's better to do this

b = f()

if(isinstance(b, tuple)):
    foo = b[0]
like image 122
ハセン Avatar answered Jun 04 '26 23:06

ハセン



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!