Pythonic编写函数的方式

时间:2018-11-15 05:04:44

标签: python python-3.x google-api

我是python的新手,并编写了一个函数来生成坐标。谁能解释一下,以pythonic方式有效重写功能的正确方法是什么。

def generate_lat_long(location):
    coordinates = {}
    coordinates_blank = {"latitude": None,
                         "longitude": None}
    if location:
        geolocator = GoogleV3(botsetting.GOOGLE_API_KEY)
        location_raw = geolocator.geocode(location, language='en')
        if location_raw:
            coordinates['latitude'] = location_raw.latitude
            coordinates['longitude'] = location_raw.longitude

            print("printing coordinated from google ap1", coordinates)
            return coordinates
        else:
            return coordinates_blank

    else:

        return coordinates_blank

除此之外,我还收到以下异常

   Traceback (most recent call last):
  File "/home/embed/PycharmProjects/slack_grocerbot/BotUtils.py", line 31, in <module>
    generate_lat_long('kolkata')
  File "/home/embed/PycharmProjects/slack_grocerbot/BotUtils.py", line 15, in generate_lat_long
    latitude = location.latitude
AttributeError: 'str' object has no attribute 'latitude'

谢谢

1 个答案:

答案 0 :(得分:2)

我认为,如果您仅打算返回多个值,则应避免使用dict。只需返回两个值的tuple

from typing import Tuple, Optional


def generate_lat_long(location: str) -> Tuple[Optional[float], Optional[float]]:
    coordinates_blank = (None, None)

    if not location:
        return coordinates_blank

    geolocator = GoogleV3(botsetting.GOOGLE_API_KEY)
    location_raw = geolocator.geocode(location, language='en')

    if not location_raw:
        return coordinates_blank

    print("printing coordinated from google ap1", coordinates)
    return (location_raw.latitude, location_raw.longitude)

然后在函数外部像这样使用它:

lat, lon = generate_lat_long('some place')

您还可以使用类型提示(诸如location: str-> Tuple[...]之类的可选提示)来注释您的函数期望得到什么以及它将返回什么。