vendredi 18 septembre 2020

Python: Cleanest Way to Run Cascading Functions if Previous Function Returned None

Essentially, I have a 3 separate functions. I want to run geopy_parse first, and if it returns None, then I'll run libpostal_parse, and if that returns None, I'll finally run the last function google_maps_parse. The final return of the function should be the result of the last sub-function that was run. I have created a function that accomplishes this, but I would like to rewrite it in a cleaner more pythonic way.

Code Example:

def parse_address(address_str):
    # if no address string provided, return None result
    if not address_str:
        return (None, None, None)
    
    # execute geopy parser
    res = geopy_parse(address_str)
    
    if not res:
        res = libpostal_parse(address_str)
    if not res:
        res = google_maps_parse(address_str)
    
    return {
        'nation': res['country'],
        'state': res['state'],
        'city': res['city'] or res['town'] or res['county']
        } 

Aucun commentaire:

Enregistrer un commentaire