About Functions Returning Multiple Values

When you need to return multiple values by a function, use named tuple for the most flexibility.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from collections import namedtuple

Geoposition = namedtuple("Geoposition", ["latitude", "longitude"])

def get_location_geoposition(location_id):
    location = Location.objects.get(pk=location_id)
    return Geoposition(location.latitude, location.longitude)


latitude, longitude = get_location_geoposition(1)
print(latitude)
print(longitude)

geoposition = get_location_geoposition(2)
print(geoposition.latitude)
print(geoposition.longitude)

Tips and Tricks Programming Python 3