NoneType 位于何处?

新手上路,请多包涵

在 Python 3 中,我想检查 value 是字符串还是 None

一种方法是

assert type(value) in { str, NoneType }

但是 NoneType 位于 Python 中的哪里?

没有任何进口,使用 NoneType 产生 NameError: name 'NoneType' is not defined

原文由 Tregoreg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

types.NoneType 在 Python 3.10 中重新引入。

Python 3.10 中的新功能

改进模块

类型

重新引入了 types.EllipsisTypetypes.NoneTypetypes.NotImplementedType 类,提供了一组易于类型检查器解释的新类型。 (由 Bas van Beek 在 bpo-41810 中贡献。)

关于更改的讨论是出于对 types.EllipsisType 的需要,导致 types.NoneType 也被 添加以保持一致性

原文由 bad_coder 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 type(None) 来获取类型对象,但是您想在这里使用 isinstance() 而不是 type() in {...}

 assert isinstance(value, (str, type(None)))

NoneType 对象不会在 3.10*之前的 Python 版本中以其他方式公开。

我根本不会为此使用类型检查,我会使用:

 assert value is None or isinstance(value, str)

因为 None 是单例(非常有目的的)和 NoneType 明确禁止子类化:

 >>> type(None)() is None
True
>>> class NoneSubclass(type(None)):
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: type 'NoneType' is not an acceptable base type


*从 Python 3.10 开始,您可以使用 types.NoneType ,以与 添加到 types 模块的其他单例类型 保持一致。

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题