I'm passing an argument to a function such that I want to delay giving the default parameter, in the usual way:
def f(x = None):
if x == None:
x = ...
The only problem is that x
is likely to be a numpy array. Then x == None
returns a boolean array, which I can't condition on. The compiler suggests to use .any()
or .all()
But if I write
def f(x = None):
if (x == None).any():
x = ...
this won't work if x
goes to its default value, because then None == None
is a Boolean, which has no .any()
or .all()
methods. What's my move here?
When comparing against None
, it is a good practice to use is
as opposed to ==
. Usually it doesn't make a difference, but since objects are free to implement equality any way they see fit, it is not always a reliable option.
Unfortunately, this is one of those cases where ==
doesn't cut it, since comparing to numpy arrays returns a boolean mask based on the condition. Luckily, there is only a single instance of None
in any given Python program, so we can actually check the identity of an object using the is
operator to figure out if it is None
or not.
>>> None is None
True
>>> np.array([1,2,3]) is None
False
So no need for any
or all
, you can update your function to something like:
def f(x=None):
if x is None:
print('None')
else:
print('Not none')
In action:
>>> f()
None
>>> f(np.array([1,2,3]))
Not none
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With