问题:如何使用类型提示指定多种返回类型

我在python中有一个可以返回a bool或a 的函数list。有没有一种方法可以使用类型提示指定返回类型。

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

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

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

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

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

回答 0

文档中

typing.Union

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

因此,表示多个返回数据类型的正确方法是

from typing import Union


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

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

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

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

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

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

请注意,这仅适用于Python的3.5及以上。PEP 484中明确提到了这一点。

From the documentation

class typing.Union

Union type; Union[X, Y] means either X or 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.”

>>> 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.

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

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

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


回答 1

该语句def foo(client_id: str) -> list or bool:在被求值时等效于 def foo(client_id: str) -> list:并且将不会执行您想要的操作。

描述“ A或B”类型提示的本机方法是Union(由于Bhargav Rao):

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

我不想成为“您为什么仍要这样做”的家伙,但是也许您不想要2种返回类型:

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

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.

The native way to describe a “either A or B” type hint is Union (thanks to 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:

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 None could be returned with Optional[list]


回答 2

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

from typing import Tuple

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

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

In case anyone landed here in search of “how to specify types of multiple return values?”, use 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


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