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 ?