How to access the NoneType type?

后端 未结 2 1118
逝去的感伤
逝去的感伤 2021-02-07 16:19

For example looking at the type of None, we can see that it has NoneType:

>>> type(None)
NoneType

However a NameErr

相关标签:
2条回答
  • 2021-02-07 16:49

    Well, in Python 2, you can import it from the types module:

    from types import NoneType
    

    but it's not actually implemented there or anything. types.py just does NoneType = type(None). You might as well just use type(None) directly.

    In Python 3, the types.NoneType name is gone. Just use type(None).


    If type(None) shows NoneType for you, rather than something like <class 'NoneType'>, you're probably on some nonstandard interpreter setup, such as IPython. It'd usually show up as something like <class 'NoneType'>, making it clearer that you can't just type NoneType and get the type.

    0 讨论(0)
  • 2021-02-07 16:53

    As suggested by @dawg in the comments, you can do

    if (type(some_object).__name__ == "NoneType"):
      # Do some
      pass
    

    You can also do

    NoneType = type(None)    
    isinstance(some_object, NoneType) 
    
    0 讨论(0)
提交回复
热议问题