Home > Net >  Default function argument value for Numpy Arrays and lists
Default function argument value for Numpy Arrays and lists

Time:12-15

I want to define a function that determines whether an input to a function is a numpy array or list or the input is none of the two mentioned data types. Here is the code:

def test_array_is_given(arr = None):
    if arr != None:
        if type(arr) in [np.ndarray, list]:
            return True
    return False


input_junk = 12
input_list = [1,2,3,4]
input_numpy = np.array([[1,2,3],[4,5,6]])

print(test_array_is_given(input_junk))
print(test_array_is_given(input_list))
print(test_array_is_given(input_numpy))

And here is what I get:

False
True

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/gv/k2qrhzhn1tg5g_kcrnxpm3c80000gn/T/ipykernel_1992/766992758.py in <module>
     12 print(test_array_is_given(input_junk))
     13 print(test_array_is_given(input_list))
---> 14 print(test_array_is_given(input_numpy))

/var/folders/gv/k2qrhzhn1tg5g_kcrnxpm3c80000gn/T/ipykernel_1992/766992758.py in test_array_is_given(arr)
      1 def test_array_is_given(arr = None):
----> 2     if arr != None:
      3         if type(arr) in [np.ndarray, list]:
      4             return True
      5     return False

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As you can see, I set the default value for argument arr to be None. However, whenever I try to evaluate the function given a numpy array, it faces the above error.

Any ideas on how to resolve this? Thank you for your attention in advance.

CodePudding user response:

Your function might be fixes and ameloriated using isinstance built-in function as follows:

import numpy as np
def test_array_is_given(arr=None):
    return isinstance(arr, (np.ndarray, list))
print(test_array_is_given())  # False
print(test_array_is_given(np.ones(1)))  # True
print(test_array_is_given([1,2,3]))  # True

when 2nd argument is tuple that might be read as any of, in this case check if it is np.ndarray of list. No special check for None is required as it is object of class NoneType.

CodePudding user response:

Matthias points this out already: The issue is with the equality check arr != None.

When arr is a numpy array, arr != None checks if each element of arr is unequal to None and returns a np.array of boolean values.

In[1]: arr = np.array([[1,2,3],[4,5,6]])

In[2]: arr != None

Out[2]:
array([[ True,  True,  True],
       [ True,  True,  True]])

What you want to do is

In[3]: arr is not None
Out[3]: True

Generally if you want to check if a values is not None. Use: val is not None.

CodePudding user response:

Thanks to Matthias, I learnt about my problem. That is, I have to compare objects with None using is.

Now that I know about is operator, I found a stackoverflow question\answer which explains why we should choose is over == (or is not over !=).

Note: the good news is that is not also works for my case; that is, replacing it with != returns my expected values (False, True and True respectively).

  • Related