Where is the NoneType located in Python 3.x?

2020-03-01 03:39发布

问题:

In Python 3, I would like to check whether value is either string or None.

One way to do this is

assert type(value) in { str, NoneType }

But where is NoneType located in Python?

Without any import, using NoneType produces NameError: name 'NoneType' is not defined.

回答1:

You can use type(None) to get the type object, but you want to use isinstance() here, not type() in {...}:

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

The NoneType object is not otherwise exposed anywhere.

I'd not use type checking for that at all really, I'd use:

assert value is None or isinstance(value, str)

as None is a singleton (very much on purpose) and NoneType explicitly forbids subclassing anyway:

>>> 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


回答2:

Please use type(None). You can use python shell to check like in the below function in which I use type(None) in order to change from None to 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)