Python 如何创建返回列表包含字符串的类型提示?
我想在Python程序中使用类型提示。如何为复杂的数据结构创建类型提示,如Python 如何创建返回列表包含字符串的类型提示?,python,python-3.5,type-hinting,Python,Python 3.5,Type Hinting,我想在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()
- 带字符串的列表
- 返回整数的生成器
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
使用;它包含泛型和类型对象,可用于指定容器及其内容的约束:
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()
的返回值,您也可以在此处使用和类型,具体取决于您是否希望能够改变结果
生成器是一种特定类型的迭代器,因此类型化。迭代器在这里是合适的。如果生成器也接受send()
值并使用return
设置StopIteration
值,则也可以使用:
如果你是新的类型暗示,那么可能会有所帮助
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