【问题标题】:How can I create a type hint that my returned list contains strings?如何创建返回列表包含字符串的类型提示?
【发布时间】:2016-09-20 01:39:13
【问题描述】:

我想在我的 Python 程序中使用类型提示。如何为像

这样的复杂数据结构创建类型提示
  • 字符串列表
  • 返回整数的生成器?

示例

def names() -> list:
    # I would like to specify that the list contains strings?
    return ['Amelie', 'John', 'Carmen']

def numbers():
    # Which type should I specify for `numbers()`?
    for num in range(100):
        yield num    

【问题讨论】:

    标签: python python-3.5 type-hinting


    【解决方案1】:

    使用typing module;它包含 generics,类型对象可用于指定容器并对其内容进行约束:

    import typing
    
    def names() -> typing.List[str]:  # list object with strings
        return ['Amelie', 'John', 'Carmen']
    
    def numbers() -> typing.Iterator[int]:  # iterator yielding integers
        for num in range(100):
            yield num
    

    根据您设计代码的方式以及您希望如何使用names() 的返回值,您还可以在此处使用types.Sequencetypes.MutableSequence 类型,具体取决于您是否希望能够改变结果。

    生成器是一种特定类型的迭代器,所以typing.Iterator 在这里是合适的。如果您的生成器也接受send() 值并使用return 设置StopIteration 值,您也可以使用typing.Generator object

    def filtered_numbers(filter) -> typing.Generator[int, int, float]:
        # contrived generator that filters numbers; returns percentage filtered.
        # first send a limit!
        matched = 0
        limit = yield
        yield  # one more yield to pause after sending
        for num in range(limit):
            if filter(num):
                yield num
                matched += 1
        return (matched / limit) * 100
    

    如果您不熟悉类型提示,那么PEP 483 – The Theory of Type Hints 可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-10-08
      • 2012-01-17
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多