我该如何创建一个类型提示,以表明我的返回列表包含字符串?

19

我想在我的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    
2个回答

27

使用typing模块,它包含泛型,类型对象,您可以使用它来指定具有对其内容的约束条件的容器:

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()返回值的使用方式,你也可以在这里使用typing.Sequencetyping.MutableSequence类型,具体取决于你是否期望能够改变结果。

生成器是一种特殊类型的迭代器,因此在这里适用typing.Iterator。如果你的生成器还接受send()值并使用return设置StopIteration值,那么也可以使用typing.Generator对象

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 可能会有所帮助。

2

自Python 3.9开始,您可以使用以下语法。不再需要导入typing模块。

def names() -> list[str]:

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接