Search code examples
pythonooptyping

Is there any built in lambda for is notNone in python


I see the following idiom repeated several times in python X = filter(lambda x: x is not None, X))

I was hoping there is a builtin function for is not None(in its standard library or something similar to apache-commons for java) in python.

In my code I have organized it as

def isNotNone(X: Any) -> bool:
    return True if X is not None else False

X = filter(isNotNone, X)

Solution

  • You could use None.__ne__, i.e. the not-equal check of None:

    >>> lst = [0, [], None, ""]
    >>> list(filter(None.__ne__, lst))
    [0, [], '']
    

    Technically, this does not test x is not None but x != None, which could yield a different result for some cases, e.g. for classes that compare equal to None, but for most practical cases, it should probably work.


    As noted in comments, this does not behave the same -- or is not even defined -- for all versions of Python, some properly returning True or False and others yielding NotImplemented for most values, which coincidentally "works", too, but should not be relied on. Instead, it's probably a better idea just to define your own def or lambda or (for this use case) use a list comprehension.