2

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 hillupillu(): #how can i check if i or j are empty? this is not doing it of course;-P
    print i,j 
3
  • and if not it returns an error...how to do it, that there will be no error? A kind of first check if there are returned values...not just a simple try, except clause..? Thanks for the comment Commented Oct 8, 2011 at 17:00
  • 3
    Something to remember: return a, b doesn't return two objects, it's equivalent to return (a, b), i.e. creates and returns a two-element tuple. Commented Oct 8, 2011 at 17:02
  • 1
    @Jurudocs no need, just let the error happen, then you will know where it happened by checking the Trackback Commented Oct 8, 2011 at 17:05

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

6 Comments

can i make a previous check, if there is a value...or is it just not neccessary or common?
@Jurudocs: You can do r = hillupillu() and then later "unpack" into two variables with i, j = r.
@Jurudocs: however, seasoned Pythonistas will tell you that "it's easier to ask forgiveness than permission"; if you have the option, then let the program throw an exception and handle that instead of writing your own checks.
@larsmans: what if something else raises ValueError in hillupillu(). How do you separate these cases?
This is dangerous for strings. It will work fine if the function returns a string with exactly 2 characters.
|
8

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

2 Comments

The if checks aren't reliable in every case, e.g. the function might return a single bool or number (zero tests as false).
@larsmans: This code checks the length of the returned tuple as it says. In general functions should not return incompatible types. For example, any sequence might be an acceptable return value in this case but an integer is not.
0

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

2 Comments

Testing the truth value may not always work. Sometimes you want to distinguish between True, False and None; sometimes you want to return a number or None.
Of course. I added this since the question tried to use this test.
0
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

5 Comments

Don't compare to None using equality operator, use is.
No need for the parentheses. Also, checking for if is usually done with is rather than ==. This is not C.
this is how i code in python, i think the operands "==" are easier to read for myself, just what ever floats ur boat i suppose
is is more reliable with arbitrary objects from untrusted libraries. And you're violating PEP-20, rules 7 and 13.
well that is if u follow the zen python rules, not sure why it's a big deal to you, but like i said it's what ever floats ur boat
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.