liveBook · Manning

Return value

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

A function return value is the object supplied by a function to the caller when the function completes.

A return value is the object a function supplies to its caller when it completes. It forms part of an API’s output contract alongside system actions and exceptions. Applications commonly orchestrate function calls by feeding returned values into later functions. section 3.1.3

Useful properties of return values include:

  • Because Python functions return objects, they can return tuples or other compound values rather than only scalar results. section 3.1.3
  • A function without an explicit return statement returns None automatically; functions performing system actions can return True or False to report success or failure. section 3.2.3
  • Returning data instead of printing it keeps a function reusable and makes its behavior easier to test. section 3.2.4

Returning and unpacking multiple values

abs(-10) returns 10. A split_fullname function can return a three-item tuple, allowing callers to write fname, mname, lname = split_fullname("John James Smith"). The caller may also retain the result as one tuple. section 3.1.3

def full_name(fnameNone, mname=None, lname=None) -> str:
    """Concatenates the names together and returns the full name
    
    Arguments:
        fname {str} -- first name
        mname {str} -- middle name
        lname {str} -- last name
    
    Returns:
        str -- the full name with only a single space between names
    """
    full_name = " ".join(name for name in [fname, mname, lname] if name)
    return full_name

Prefer a focused function that returns the constructed full name; callers can print it, place it in a web page or data structure, convert it to JSON, and test it directly. section 3.2.4

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains scalar results, compound tuples, implicit None, status flags, unpacking, reuse, and testability.
Examples
Uses abs, split_fullname tuple unpacking, and a full_name refactoring from printing to returning.
What you can do after
Apply it by returning reusable data, unpacking compound results, reporting operation status, and testing outputs directly.
How it connects
Connects return values with APIs, parameters, tuples, side effects, exceptions, single responsibility, and testing.

Also explained in

Compare how 8 books explain return value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.