Use the typing module https://docs.python.org/3/library/typing.html;它包含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.Sequence https://docs.python.org/3/library/typing.html#typing.Sequence and types.MutableSequence https://docs.python.org/3/library/typing.html#typing.MutableSequence此处的类型,具体取决于您是否期望能够改变结果。
生成器是一种特定类型的iterator, so typing.Iterator
放在这里是合适的。如果您的发电机也接受send()
价值和用途return
设置一个StopIteration
值,您可以使用typing.Generator object https://docs.python.org/3/library/typing.html#typing.Generator too:
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 –类型提示理论 https://www.python.org/dev/peps/pep-0483/可能会有帮助。