Are there any built-in lambda for is notNone in python
I’ve seen the following idiom repeated a few times in python X = filter(lambda x: x is not none, X)).
I wish there was a built-in function in python for is not none
(in its standard library or something like java’s apache-commons).
In my code, I organize it as
def isNotNone(X: Any) -> bool:
return True if X is not None else False
X = filter(isNotNone, X)
Solution
You can use None.__ne__
, which is the inequality check of None
:
>>> lst = [0, [], None, ""]
>>> list(filter(None.__ne__, lst))
[0, [], '']
Technically, this doesn’t test x is not None
but x !=
None, and may produce different results in some cases, such as for classes that compare equal to None
, but it should work for most real-world cases.
As noted in the review, this is not the same for all versions of Python – or even defined – some correctly return True
or False
and others produce NotImplemented
for most values, which is also coincidentally “valid” but should not be relied upon. Instead, it might be a better idea to define your own def
or lambda
or, for this use case, use list understanding.