Where is the NoneType located in Python 3.x?

前端 未结 3 1631
孤城傲影
孤城傲影 2020-12-17 08:32

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


        
3条回答
  •  独厮守ぢ
    2020-12-17 09:01

    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 "", line 1, in 
    TypeError: type 'NoneType' is not an acceptable base type
    

提交回复
热议问题