Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning a tuple or None: how to call that function nicely?

Suppose the following:

def MyFunc(a):
  if a < 0:
    return None
  return (a+1, a+2, a+3)

v1, v2, v3 = MyFunc()
# Bad ofcourse, if the result was None

What is the best way to define a function that returns a tuple and yet can be nicely called. Currently, I could do this:


r = MyFunc()
if r:
  v1, v2, v3 = r
else:
  # bad!!
  pass

What I don't like about this is that I have to use a single variable and then unpack it.

Another solution is I could have the function return a tuple full of Nones so that the caller can nicely unpack....

Anyone can suggest a better design?

like image 200
Elias Bachaalany Avatar asked Aug 10 '10 12:08

Elias Bachaalany


People also ask

Can a function return a tuple?

Functions can return tuples as return values.

What is a correct way of returning the number of items in a tuple?

Python tuple method len() returns the number of elements in the tuple.

Can you return two different types in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

What does it mean for a function to return None?

If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None. Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.


2 Answers

How about raise an ArgumentError? Then you could try calling it, and deal with the exception if the argument is wrong.

So, something like:

try:
    v1, v2, v3 = MyFunc()
except ArgumentError:
    #deal with it

Also, see katrielalex's answer for using a subclass of ArgumentError.

like image 56
Skilldrick Avatar answered Oct 16 '22 00:10

Skilldrick


This should work nicely:

v1, v2, v3 = MyFunc() or (None, None, None)

When MyFunc() returns a tuple, it will be unpacked, otherwise it will be substituted for a 3-tuple of None.

like image 39
recursive Avatar answered Oct 15 '22 23:10

recursive