Search code examples
pythonpython-3.xnonetype

Why does this lambda function always return False even when the type matches?


Given:

type(m[11].value)
<class 'NoneType'>

type(m[12].value)
<class 'str'>

Why then does the following lambda function always return false when I pass it the two above vars?

g = lambda x: type(x) is None

Solution

  • You're checking whether the type of an object is None, and not the actual object itself. type returns a type object, the actual type/class of that object. In the particular case of None, it returns NoneType:

    >>> type(None)
    NoneType
    

    Since object has a type, type(x) is None will never evaluate to True.

    Why not just test the object directly? Additionally, if you are going to name a lambda, you may as well define your own function.

    >>> def check(x):
    ...     return x is None
    ... 
    >>> check(None)
    True  
    

    Alternatively, you may use an isinstance check -

    >>> isinstance(None, type(None))
    True
    

    As a side note, the pd.isnull function from the pandas library provides this functionality directly.