如何创建返回的列表包含字符串的类型提示? [英] How can I create a type hint that my returned list contains strings?
问题描述
我想在我的 Python 程序中使用类型提示.如何为复杂的数据结构(如
I want to use Type Hints in my Python program. How can I create Type Hints for complex data structures like
- 带字符串的列表
- 返回整数的生成器?
示例
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
推荐答案
使用 typing
模块;它包含泛型,您可以使用类型对象来指定对其内容有约束的容器:
Use the typing
module; it contains generics, type objects you can use to specify containers with constraints on their contents:
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
和 types.MutableSequence
类型在这里,取决于您是否希望能够改变结果.
Depending on how you design your code and how you want to use the return value of names()
, you could also use the types.Sequence
and types.MutableSequence
types here, depending on wether or not you expect to be able to mutate the result.
生成器是一种特定类型的迭代器,所以 typing.Iterator
在这里是合适的.如果您的生成器也接受 send()
值并使用 return
来设置 StopIteration
值,您可以使用 typing.Generator
对象也是:
A generator is a specific type of iterator, so typing.Iterator
is appropriate here. If your generator also accepts send()
values and uses return
to set a StopIteration
value, you can use the typing.Generator
object 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 – 类型提示理论 可能会有所帮助.
If you are new to type hinting, then PEP 483 – The Theory of Type Hints may be helpful.
这篇关于如何创建返回的列表包含字符串的类型提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!