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?
Functions can return tuples as return values.
Python tuple method len() returns the number of elements in the tuple.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With