1.4.4 Multiple return values
1.4.4 Multiple return values mrs110It happens quite often that you want to return multiple things as the result of a function, but a function can only have one return value. To work with the single return value, we simply return a tuple, list, or dictionary with the different components you want to return. For instance, returning four coordinates describing the bounding box of a polygon, we can return a tuple with the four coordinates. Python has a useful mechanism to help with unpacking this single return value by allowing us to assign the elements of a tuple (or other sequences like lists) to several variables in a single assignment. Given a tuple (12, 3, 2, 2) assigned to t, instead of writing
t = (12, 3, 2, 2)
top = t[0]
left = t[1]
bottom = t[2]
right = t[3] you can write
top, left, bottom, right = t and it will have the exact same effect. The following example illustrates how this can be used with a function that returns a tuple of multiple return values. For simplicity, the function computeBoundingBox() in this example only returns a fixed tuple rather than computing the actual tuple values from a polygon given as input parameter.
def computeBoundingBox():
return (12,3,41,32)
top, left, bottom, right = computeBoundingBox() # assigns the four elements of the returned tuple to individual variables
print(top) # output: 12Or as a dictionary, which can also provide some insights into calculated results:
def computeBoundingBox(x):
if x==1:
return {'top':12, 'left':3,' bottom':41, 'right':32, 'success':True}
else:
return {'top':12, 'left':3, 'bottom':41, 'right':32, 'success':False}
bbox = computeBoundingBox(1) # returns the result as a dictionary
if bbox.get('success'): # if the process succeeds
print(bbox['top']) # output: 12