None Python error/bug?

前端 未结 4 2047
忘了有多久
忘了有多久 2021-02-05 07:33

In Python you have the None singleton, which acts pretty oddly in certain circumstances:

>>> a = None
>>> type(a)


        
相关标签:
4条回答
  • 2021-02-05 07:43

    None is the just a value of types.NoneType, it's not a type.

    And the error is clear enough:

    TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

    From the docs:

    None is the sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

    You can use types.NoneType

    >>> from types import NoneType
    >>> isinstance(None, NoneType)
    True
    

    is operator also works fine:

    >>> a = None
    >>> a is None
    True
    
    0 讨论(0)
  • 2021-02-05 07:51

    None is not a type, it is the singleton instance itself - and the second argument of isinstance must be a type, class or tuple of them. Hence, you need to use NoneType from types.

    from types import NoneType
    print isinstance(None, NoneType)
    print isinstance(None, (NoneType, str, float))
    
    True
    True
    

    Although, I would often be inclined to replace isinstance(x, (NoneType, str, float)) with x is None or isinstance(x, (str, float)).

    0 讨论(0)
  • 2021-02-05 07:51

    None is a value(instance) and not a type. As the error message shows, isinstance expects the second argument to be a type.

    The type of None is type(None), or Nonetype if you import it (from types import NoneType)

    Note: the idiomatic way to do the test is variable is None. Short and descriptive.

    0 讨论(0)
  • 2021-02-05 07:57

    You can try:

    >>> variable = None
    >>> isinstance(variable,type(None))
    True
    >>> variable = True
    >>> isinstance(variable,type(None))
    False
    

    isinstance takes 2 arguments isinstance(object, classinfo) Here, by passing None you are setting classinfo to None, hence the error. You need pass in the type.

    0 讨论(0)
提交回复
热议问题