Python抛出异常并返回默认值

2024-06-30 15:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用geopy的GoogleV3编写一个函数,从经纬度获取地址:

from retrying import retry
@retry(wait_exponential_multiplier=500, wait_exponential_max=4000, stop_max_attempt_number=5)
def get_address(lat, lon):
    state = 'unknown'
    country = 'unknown'
    geo = GoogleV3(api_key='my-secret-api-key')
    location = geo.reverse((lat, lon), timeout=10, exactly_one=True)
    if location == None:
        raise ValueError('a valid location for %d, %d is not found' % (lat, lon))
    for item in location.raw['address_components']:
        if u'administrative_area_level_1' in item[u'types']:
            state = item['short_name']
        if u'country' in item[u'types']:
            country = item['long_name']
    return state, country

此处的retrying装饰器将在出现异常时自动重试。这里我想引发一个异常,以指示给定的lon和{}无效,同时将country和{}都返回为“unknown”。我想知道在Python中是否有这样的方法。在


Tags: iniflocationitemcountrymaxunknownstate