Python 如何使用类型提示指定“可为空”返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39429526/
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
How to specify "nullable" return type with type hints
提问by exfizik
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
?
我如何为可以是的东西指定返回类型None
?
回答by Dimitris Fasarakis Hilliard
You're looking for Optional
.
您正在寻找Optional
.
Since your return type can either be datetime
(as returned from datetime.utcnow()
) or None
you should use Optional[datetime]
:
由于您的返回类型可以是datetime
(从 返回datetime.utcnow()
),或者None
您应该使用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
是简写:
Optional[X]
is equivalent toUnion[X, None]
.
Optional[X]
相当于Union[X, None]
。
where Union[X, Y]
means a value of type X
or Y
.
whereUnion[X, Y]
表示类型为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
:
如果您因为担心其他人可能会偶然发现Optional
而没有意识到它的含义而想要明确,您可以始终使用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.
但我怀疑这是一个好主意,Optional
是一个指示性名称,它确实节省了几次击键。
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.
正如@Michael0x2a 的评论中指出的那样,Union[T, None]
已转换为Union[T, type(None)]
因此无需在type
此处使用。
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__
*:
从视觉上看,这些可能不同,但在编程上,在这两种情况下,结果完全相同;Union[datetime.datetime, NoneType]
将是存储在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.
*用typing.get_type_hints
抢的对象的__annotations__
直接访问它的属性来代替。