开发者

Python basics: How to check if a function returns mutiple values?

Basic stuff I kn开发者_StackOverflowow...;-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 hillupillu(): #how can i check if i or j are empty? this is not doing it of course;-P
    print i,j 


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()
if len(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.


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


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: ...


if(i == "" or j == ""):
   //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


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

r_value = foo(False)

x, y = None, None
if type(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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜