jphollowed jphollowed - 3 months ago 14
Python Question

FutureWarning when comparing a NumPy object to "None"

I have a function that receives some arguments, plus some optional arguments. In it, the action taken is dependent upon whether the optional argument

c
was filled:

def func(a, b, c = None):

doStuff()

if c != None:
doOtherStuff()


If
c
is not passed, then this works fine. However, in my context, if
c
is passed, it will always be a
numpy
array. And comparing
numpy
arrays to
None
yields the following warning:

FutureWarning: comparison to `None` will result in an elementwise object comparison in the future.


So, what is the cleanest and most general way to check whether or not
c
was passed or not without comparing to
None
?

Answer

Use if c is not None instead. In addition to avoiding the warning, this is generally considered best-practice.