Search code examples
pythonlisterror-handlingtry-exceptgeopy

Returning a list of items that are raising an AttributeError when using geopy and try/except?


I am attempting to get the latitude and longitude for ~400 locations using geopy. However, many of the addresses are returning 'None' as they are either not specific enough or are intersections of streets, which is causing an "AttributeError: 'None' type has no attribute 'latitude'" and an exit of the for loop.

What I would like to do is run the for loop without exiting due to error AND return a list of all of the locations prompting errors so that I can hard code a proper address for them.

My current code is as follows:

from geopy.geocoders import Nominatim
geolocator = Nominatim()
coordinates = []

def station_errors(list_of_stations):
    for station in list_of_stations:
        try:
            location = geolocator.geocode(str(i)) #line with error, used 'i' instead of 'station'
            lat_long = (location.latitude, location.longitude)
            coordinates.append(list(lat_long))
        except Exception:
            print("Error: %s"%(station))
            continue

However, this seems to be printing out every station regardless of whether geopy was able to assign it a latitude and longitude, as I've tried many of them manually. I only want the stations that raised an error/were unable to receive a lat/long coordinate.

I am fairly new to 'try, except, continue' error testing, so any advice is greatly appreciated.

EDIT:

My initial error was using 'i' instead of 'station', an error which I've left in the original question. The code that I got to work and gives me the result that I want is as follows:

def station_errors(list_of_stations):
    list_of_error_stations = []
    for station in list_of_stations:
        try:
            location = geolocator.geocode(str(station + " DC"))
            lat_long = (location.latitude, location.longitude)
            coordinates.append(list(lat_long))
        except Exception:
            list_of_error_stations.append(station)
            continue
    return(list_of_error_stations)

Solution

  • I expect that the "AttributeError: 'None' type has no attribute 'latitude'" is given in the line:

    lat_long = (location.latitude, location.longitude)
    

    thous I would transform the code in something like:

    def station_errors(list_of_stations):
        for station in list_of_stations:
            location = geolocator.geocode(str(i))
            coordinates.append([location.latitude, location.longitude] if location is not None else None)
            # or coordinates.append(list(lat_long) if location is not None else [None, None])
            # which ever comes more in handy
        return coordinates
    
    coords = station_errors(los)
    # and then deal with the Nones (or [None, None] s ) to "hard code a proper address for them"