0

While developing a class that uses numpy.array, I'd like to construct this array at one stage, and later check whether it exists in order to manipulate it, or construct it at a later stage (pseudo-code below). How could I check that this array exists ?

For any basic object, I use : if my_object: # do something which uses the truth value testing, but for numpy the truth value testing checks whether any or all elements of the array is present, so if my_array: # do something gives the error The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

At the moment, the only working turn-around is to call isinstance(my_array,numpy.ndarray), but I think this is not really convenient (especially because some librairies like sklearn can turn numpy array to scipy.sparse objects for instance).

The pseudo-code to illustrate what I'd like to do :


def compute_my_array(self, ...):
   # long job here
   return my_array

def new_computation(self, my_array = None, ...):
   if not my_array: # if my_array does not exist, compute it ...
      my_array = compute_my_array(self, ...)
   do_something_else_with_my_array(my_array) # ... otherwise use it

For the moment the only way I found to check whether my_array exists is to use

   if not isinstance(my_array, numpy.ndarray):
      my_array = compute_my_array(my_array)

Is there any other (perhaps better) ways to do that check ?

FraSchelle
  • 249
  • 4
  • 10
  • Obviously, `if my_array is not None` does the job... is there any more pythonic way to go over this problem ? – FraSchelle Oct 27 '20 at 09:20
  • Does this answer your question? [How can I check whether the numpy array exists already or not?](https://stackoverflow.com/questions/35541595/how-can-i-check-whether-the-numpy-array-exists-already-or-not) – amzon-ex Oct 27 '20 at 09:21
  • 1
    `if my_array is None:` (which is what you want there) is perfectly pythonic – Daniel F Oct 27 '20 at 12:09
  • @DanielF Yes it is, but my main problem is whether a numpy array or a scipy.sparse matrix is empty or not, so it's not really the same problem. But surely I can use that trick. Thank you. – FraSchelle Oct 27 '20 at 13:06
  • @amzon-ex Thank you for pointing to this anwser. It doesn't really solve my problem, since I'd like to know whether an object that could be either a scipy.sparse or a numpy.array is empty or not. But yes, going though the object.shape check can be an option. I'm nevertheless looking for something more direct. – FraSchelle Oct 27 '20 at 13:07

1 Answers1

1

Just change your default to return an empty array, and then check if there's anything in the array

def new_computation(self, my_array = np.zeros((1,)), ...):
   if not my_array.any(): # if my_array has no nonzero data, compute it ...
      my_array = compute_my_array(self, ...)
   do_something_else_with_my_array(my_array) # ... otherwise use it
Daniel F
  • 13,620
  • 2
  • 29
  • 55