Python 如何使用类型提示指定多个返回类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33945261/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:13:45  来源:igfitidea点击:

How to specify multiple return types using type-hints

pythonpython-3.xreturn-typetype-hintingpython-3.5

提问by Yahya Uddin

I have a function in python that can either return a boolor a list. Is there a way to specify the return types using type hints.

我在 python 中有一个函数,它可以返回 abool或 a list。有没有办法使用类型提示指定返回类型。

For example, Is this the correct way to do it?

例如,这是正确的做法吗?

def foo(id) -> list or bool:
      ...

采纳答案by Bhargav Rao

From the documentation

文档

class typing.Union

Union type; Union[X, Y] means either X or Y.

班级 typing.Union

联合类型;Union[X, Y] 表示 X 或 Y。

Hence the proper way to represent more than one return data type is

因此,表示不止一种返回数据类型的正确方法是

from typing import Union


def foo(client_id: str) -> Union[list,bool]


But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."

但请注意,不强制输入。Python 仍然是一种动态类型语言。注释语法的开发是为了在发布到生产环境之前的代码开发过程中提供帮助。正如 PEP 484 所述,“运行时不进行类型检查”。

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

As you can see I am passing a int value and returning a str. However the __annotations__will be set to the respective values.

如您所见,我正在传递一个 int 值并返回一个 str。但是,__annotations__将设置为相应的值。

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}


Please Go through PEP 483for more about Type hints. Also see What are Type hints in Python 3.5?

请通过PEP 483了解有关类型提示的更多信息。另请参阅Python 3.5 中的类型提示是什么?

Kindly note that this is available only for Python 3.5and upwards. This is mentioned clearly in PEP 484.

请注意,这仅适用于Python 3.5及更高版本。这在PEP 484中有明确提到。

回答by Felk

The statement def foo(client_id: str) -> list or bool:when evaluated is equivalent to def foo(client_id: str) -> list:and will therefore not do what you want.

def foo(client_id: str) -> list or bool:评估时的语句等效于 def foo(client_id: str) -> list:并且因此不会执行您想要的操作。

The native way to describe a "either A or B" type hint is Union(thanks to Bhargav Rao):

描述“A 或 B”类型提示的原生方式是Union(感谢 Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

我不想成为“你为什么要这样做”的人,但也许有 2 种返回类型不是你想要的:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that Nonecould be returned with Optional[list]

如果您想返回一个 bool 来指示某种类型的特殊错误情况,请考虑改用 Exceptions。如果你想返回一个 bool 作为一些特殊值,一个空列表可能是一个很好的表示。您还可以表示None可以返回Optional[list]

回答by Anton Khodak

In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]

如果有人在这里搜索“如何指定多个返回值的类型?”,请使用 Tuple[type_value1, ..., type_valueN]

from typing import Tuple

def f() -> Tuple[dict, str]:
    a = {1: 2}
    b = "hello"
    return a, b

More info: https://code-examples.net/en/q/2651e60

更多信息:https: //code-examples.net/en/q/2651e60