在Python 3.x中,NoneType位于哪里?

2024-04-20 10:14:21 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python 3中,我想检查value是string还是None

一种方法是

assert type(value) in { str, NoneType }

但是NoneType在Python中位于哪里?

如果没有任何导入,使用NoneType将生成NameError: name 'NoneType' is not defined


Tags: 方法nameinnonestringisvaluetype
2条回答

请使用type(None)。您可以在下面的函数中使用python shell进行类似的检查,我在该函数中使用type(None),以便从None更改为NoneType

def to_unicode(value):
'''change value to unicode'''
try:
    if isinstance(value, (str,type(None))):
        return value
    if not isinstance(value, bytes):
        raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
    return value.decode("utf-8")
except UnicodeDecodeError:
    return repr(value)

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

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

NoneType对象在任何地方都不会公开。

我根本不使用类型检查,真的,我会使用:

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

相关问题 更多 >