问题:如何注释多个返回值的类型?

我如何使用类型提示来注释一个返回Iterable总是返回两个值的函数:abool和a str?提示Tuple[bool, str]很接近,除了将返回值类型限制为元组,而不是生成器或其他可迭代类型。

我主要是好奇的,因为我想注释一个foo()用于返回多个值的函数,如下所示:

always_a_bool, always_a_str = foo()

通常函数喜欢foo()做这样的事情return a, b(它返回一个元组),但我喜欢的类型暗示要足够灵活,以取代生成器或列表或别的东西返回的元组。

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.

I’m mostly curious because I would like to annotate a function foo() that is used to return multiple values like this:

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.


回答 0

您总是返回一个对象;使用return one, two只需返回一个元组。

是的,-> Tuple[bool, str]完全正确。

只有Tuple类型可以指定一个固定数量的元素,每一个不同的类型。如果您的函数产生固定数量的返回值,尤其是当这些值是特定的,不同的类型时,确实应该总是返回一个元组。

期望其他序列类型具有可变数量元素的一种类型规范,因此typing.Sequence此处不适用。另请参阅列表和元组之间有什么区别?

元组是异构数据结构(即,它们的条目具有不同的含义),而列表是同类序列。元组具有结构,列表具有顺序。

Python的类型提示系统遵循这一理念,目前尚无语法来指定固定长度的可迭代对象,并在特定位置包含特定类型。

如果必须指定任何可迭代的对象,那么最好的方法是:

-> Iterable[Union[bool, str]]

在这一点上,调用者可以期望布尔值和字符串以任意顺序,并且长度未知(0到无穷大之间)。

You are always returning one object; using return one, two simply returns a tuple.

So yes, -> Tuple[bool, str] is entirely correct.

Only the Tuple type lets you specify a fixed number of elements, each with a distinct type. You really should be returning a tuple, always, if your function produces a fixed number of return values, especially when those values are specific, distinct types.

Other sequence types are expected to have one type specification for a variable number of elements, so typing.Sequence is not suitable here. Also see What’s the difference between lists and tuples?

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.

If you must specify 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).


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。