Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a default argument after with None: what if it's an array?

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?

like image 559
Eric Auld Avatar asked Sep 17 '25 06:09

Eric Auld


1 Answers

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
like image 127
user3483203 Avatar answered Sep 19 '25 19:09

user3483203