问题描述
假设我有一个函数:
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]
表示 X
或 Y
类型的值.
如果您担心其他人可能会偶然发现 Optional
而没有意识到它的含义而想要明确,则可以始终使用 Union
:
from 打字 import Uniondef get_some_date(some_argument: int=None) ->联合[日期时间,无]:
但我怀疑这是一个好主意,Optional
是一个指示性名称,它确实节省了几次按键操作.
在视觉上这些可能不同,但在编程上,在这两种情况下,结果完全相同;Union[datetime.datetime, NoneType]
将是存储在 get_some_date.__annotations__
中的类型:
使用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:
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.
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.
这篇关于如何指定“可为空"带类型提示的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!