Jon*_*Jon 17 python type-hinting python-3.5
我想在我的Python程序中使用Type Hints.如何为复杂的数据结构创建类型提示
例
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
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 20
使用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
Run Code Online (Sandbox Code Playgroud)
根据您设计代码的方式以及如何使用返回值names(),您还可以使用此处的types.Sequence和types.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
Run Code Online (Sandbox Code Playgroud)
如果您不熟悉提示,那么PEP 483 - 类型提示理论可能会有所帮助.