Python 如何注释多个返回值的类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40181344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to annotate types of multiple return values?
提问by Richard Hansen
How do I use type hints to annotate a function that returns an Iterable
that always yields two values: a bool
and a str
? The hint Tuple[bool, str]
is close, except that it limits the return value type to a tuple, not a generator or other type of iterable.
我如何使用类型提示来注释一个返回 an 的函数,该函数Iterable
总是产生两个值: abool
和 a str
?提示Tuple[bool, str]
很接近,除了它将返回值类型限制为元组,而不是生成器或其他类型的可迭代对象。
I'm mostly curious because I would like to annotate a function foo()
that is used to return multiple values like this:
我很好奇,因为我想注释一个foo()
用于返回多个值的函数,如下所示:
always_a_bool, always_a_str = foo()
Usually functions like foo()
do something like return a, b
(which returns a tuple), but I would like the type hint to be flexible enough to replace the returned tuple with a generator or list or something else.
通常函数像foo()
做类似的事情return a, b
(返回一个元组),但我希望类型提示足够灵活,可以用生成器或列表或其他东西替换返回的元组。
回答by Martijn Pieters
You are always returning oneobject; using return one, two
simply returns a tuple.
你总是返回一个对象;usingreturn one, two
简单地返回一个元组。
So yes, -> Tuple[bool, str]
is entirely correct.
所以是的,-> Tuple[bool, str]
完全正确。
Onlythe Tuple
type lets you specify a fixed numberof elements, each with a distinct type. You really should be returning a tuple, always, if your function produces a fixednumber of return values, especially when those values are specific, distinct types.
只有该Tuple
类型可以指定一个固定数量的元素,每一个不同的类型。如果您的函数产生固定数量的返回值,您真的应该始终返回一个元组,尤其是当这些值是特定的、不同的类型时。
Other sequence types are expected to have onetype specification for a variable number of elements, so typing.Sequence
is not suitable here. Also see What's the difference between lists and tuples?
其他序列类型预计对可变数量的元素有一个类型规范,所以typing.Sequence
在这里不合适。另请参阅列表和元组之间的区别是什么?
Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.
元组是异构的数据结构(即它们的条目具有不同的含义),而列表是同构的序列。元组有结构,列表有顺序。
Python's type hint system adheres to that philosophy, there is currently no syntax to specify an iterable of fixed length and containing specific types at specific positions.
Python 的类型提示系统遵循这一理念,目前没有语法来指定固定长度的可迭代对象并在特定位置包含特定类型。
If you mustspecify that any iterable will do, then the best you can do is:
如果您必须指定任何可迭代对象都可以,那么您能做的最好的事情是:
-> Iterable[Union[bool, str]]
at which point the caller can expect booleans and strings in any order, and of unknown length (anywhere between 0 and infinity).
在这一点上,调用者可以期望任何顺序的布尔值和字符串,并且长度未知(0 和无穷大之间的任何位置)。