类型注释的 None 与 NoneType

问题描述 投票:0回答:1

如果函数可以返回

None
,类型注释不应该使用
NoneType
吗?

例如,我们不应该使用这个:

from types import NoneType

def my_function(num: int) -> int | NoneType:

    if num > 0:
        return num

    return None

而不是:

def my_function(num: int) -> int | None:

    if num > 0:
        return num

    return None

python python-typing nonetype
1个回答
9
投票

不。

types.NoneType
在 Python 3 中被删除。尝试从
NoneType
导入
types
将在 Python 3.10 之前的 Python 3 中生成
ImportError
。 (对于 Python 3.10,重新引入了
types.NoneType
;但是,出于类型提示的目的,
types.NoneType
None
是等效的,为了简洁起见,您应该更喜欢后者。)

Python 3.10 中,

int | None
是描述可能是
None
的返回类型的方式。但是,对于 3.10 之前的 Python 版本,不支持此语法,因此您应该使用
Optional[int]
来代替。

© www.soinside.com 2019 - 2024. All rights reserved.