Skip to content Skip to sidebar Skip to footer

Python Basics: How To Check If A Function Returns Mutiple Values?

Basic stuff I know...;-P But what is the best way to check if a function returns some values? def hillupillu(): a= None b='lillestalle' return a,b if i and j in hil

Solution 1:

If you meant that you can't predict the number of return values of some function, then

i, j = hillupillu()

will raise a ValueError if the function doesn't return exactly two values. You can catch that with the usual try construct:

try:
    i, j = hillupillu()
except ValueError:
    print("Hey, I was expecting two values!")

This follows the common Python idiom of "asking for forgiveness, not permission". If hillupillu might raise a ValueError itself, you'll want to do an explicit check:

r = hillupillu()
iflen(r) != 2:  # maybe check whether it's a tuple as well with isinstance(r, tuple)print("Hey, I was expecting two values!")
i, j = r

If you meant that you want to check for None in the returned values, then check for None in (i, j) in an if-clause.

Solution 2:

Functions in Python always return a single value. In particular they can return a tuple.

If you don't know how many values in a tuple you could check its length:

tuple_ = hillupillu()
i = tuple_[0] if tuple_ else None
j = tuple_[1] if len(tuple_) > 1 else None

Solution 3:

After receiving the values from the function:

i, j = hillupillu()

You can check whether a value is None with the is operator:

if i is None: ...

You can also just test the value's truth value:

if i: ...

Solution 4:

if(i == ""orj== ""):
   //execute code

something like that should wordk, but if your giving it a None value you would do this

if(i == None or j == None):
    //execute code

hope that helps

Solution 5:

You can check whether the return value of the function is a tuple:

r_value = foo(False)

x, y = None, Noneiftype(r_value) == tuple:
    x, y = r_value
else:
    x = r_value
    
print(x, y)

This example is suited for a case where the function is known to return either exactly one tuple of length 2 (for example by doing return a, b), or one single value. It could be extended to handle other cases where the function can return tuples of other lengths.

I don't believe @Fred Foo's accepted answer is correct for a few reasons:

  • It will happily unpack other iterables that can be unpacked into two values, such as a list or string of lengths 2. This does not correspond to a return from a function that returned multiple values.
  • The thrown exception can be TypeError, not a ValueError.
  • The variables that store the return value are scoped to the try block, and so we can only deal with them inside that block.
  • It doesn't show how to handle the case where there is a single returned value.

Post a Comment for "Python Basics: How To Check If A Function Returns Mutiple Values?"