如何指定“可为空"带类型提示的返回类型 [英] How to specify "nullable" return type with type hints

查看:54
本文介绍了如何指定“可为空"带类型提示的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个函数:

def get_some_date(some_argument: int=None) ->%datetime_or_None%:如果 some_argument 不是 None 并且 some_argument == 1:返回日期时间.utcnow()别的:返回无

如何为可以为 None 的内容指定返回类型?

解决方案

您正在寻找 可选.

由于您的返回类型可以是 datetime(从 datetime.utcnow() 返回)或 None,因此您应该使用 可选[日期时间]:

from 输入 import 可选def get_some_date(some_argument: int=None) ->可选[日期时间]:# 如定义

在打字文档中,Optional 是:

<块引用>

Optional[X] 等价于 Union[X, None].

其中 Union[X, Y] 表示 XY 类型的值.

<小时>

如果您担心其他人可能会偶然发现 Optional 而没有意识到它的含义而想要明确,则可以始终使用 Union:

from 打字 import Uniondef get_some_date(some_argument: int=None) ->联合[日期时间,无]:

但我怀疑这是一个好主意,Optional 是一个指示性名称,它确实节省了几次按键操作.

正如@Michael0x2a 在评论中指出的 Union[T, None] 被转换为 Union[T, type(None)] 所以不需要在这里使用 type.

在视觉上这些可能不同,但在编程上,在这两种情况下,结果完全相同Union[datetime.datetime, NoneType] 将是存储在 get_some_date.__annotations__* 中的类型:

<预><代码>>>>从输入导入 get_type_hints>>>打印(get_type_hints(get_some_date)){'return': typing.Union[datetime.datetime, NoneType],'some_argument':typing.Union[int, NoneType]}

*使用typing.get_type_hints 获取对象的__annotations__ 属性,而不是直接访问它.

Suppose I have a function:

def get_some_date(some_argument: int=None) -> %datetime_or_None%:
    if some_argument is not None and some_argument == 1:
        return datetime.utcnow()
    else:
        return None

How do I specify the return type for something that can be None?

解决方案

You're looking for Optional.

Since your return type can either be datetime (as returned from datetime.utcnow()) or None you should use Optional[datetime]:

from typing import Optional

def get_some_date(some_argument: int=None) -> Optional[datetime]:
    # as defined

From the documentation on typing, Optional is shorthand for:

Optional[X] is equivalent to Union[X, None].

where Union[X, Y] means a value of type X or Y.


If you want to be explicit due to concerns that others might stumble on Optional and not realize it's meaning, you could always use Union:

from typing import Union

def get_some_date(some_argument: int=None) -> Union[datetime, None]:

But I doubt this is a good idea, Optional is an indicative name and it does save a couple of keystrokes.

As pointed out in the comments by @Michael0x2a Union[T, None] is tranformed to Union[T, type(None)] so no need to use type here.

Visually these might differ but programatically, in both cases, the result is exactly the same; Union[datetime.datetime, NoneType] will be the type stored in get_some_date.__annotations__*:

>>> from typing import get_type_hints
>>> print(get_type_hints(get_some_date))
{'return': typing.Union[datetime.datetime, NoneType],
 'some_argument': typing.Union[int, NoneType]}

*Use typing.get_type_hints to grab the objects' __annotations__ attribute instead of accessing it directly.

这篇关于如何指定“可为空"带类型提示的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆