What's the best way to return multiple values from a function?

PythonVariablesReturn

Python Problem Overview


I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string.

In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string.

Related question: Is it pythonic for a function to return multiple values?

Python Solutions


Solution 1 - Python

def f(in_str):
    out_str = in_str.upper()
    return True, out_str # Creates tuple automatically

succeeded, b = f("a") # Automatic tuple unpacking

Solution 2 - Python

Why not throw an exception if the operation wasn't successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you're doing things the right way or use an object.

But more directly to the point, if you throw an exception, you're forcing them to deal with the problem. If you try to return a value that indicates failure, it's very well possible somebody could not check the value and end up with some potentially hard to debug errors.

Solution 3 - Python

Return a tuple.

def f(x):
    # do stuff
    return (True, modified_string)

success, modified_string = f(something)

Solution 4 - Python

Returning a tuple is the usual way to do this in Python.

Solution 5 - Python

Throwing an exception for failure is one good way to proceed, and if you're returning a lot of different values, you can return a tuple. For the specific case you're citing, I often take an intermediate approach: return the modified string on success, and return None on failure. I'm enough of an unreconstructed C programmer to want to return a NULL pointer to char on failure.

If I were writing a routine to be used as part of a larger library and consumed by other developers, I'd throw an exception on failure. When I'm eating my own dogfood, I'll probably return different types and test on return.

Solution 6 - Python

You can use return statement with multiple expressions

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn RutherfordView Question on Stackoverflow
Solution 1 - PythonJohn MillikinView Answer on Stackoverflow
Solution 2 - PythonJason BakerView Answer on Stackoverflow
Solution 3 - PythonrmmhView Answer on Stackoverflow
Solution 4 - PythonChris UpchurchView Answer on Stackoverflow
Solution 5 - PythontuxedoView Answer on Stackoverflow
Solution 6 - PythonSanmitha SadhishkumarView Answer on Stackoverflow