您可以使用type(None)
获取类型对象,但您想使用isinstance()
在这里,不type() in {...}
:
assert isinstance(value, (str, type(None)))
The NoneType
object is not otherwise exposed anywhere in Python versions older than 3.10 https://github.com/python/cpython/issues/85976*.
我实际上根本不会使用类型检查,我会使用:
assert value is None or isinstance(value, str)
as 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
* As of Python 3.10, you could use types.NoneType https://docs.python.org/3/library/types.html#types.NoneType, to be consistent with the other singleton types being added to the types module https://github.com/python/cpython/issues/85976.