ValueError when checking if variable is None or numpy.array

后端 未结 3 1946
感动是毒
感动是毒 2020-12-07 17:13

I\'d like to check if variable is None or numpy.array. I\'ve implemented check_a function to do this.

def check_a(a):
    if not a:
        prin         


        
相关标签:
3条回答
  • 2020-12-07 17:48

    Using not a to test whether a is None assumes that the other possible values of a have a truth value of True. However, most NumPy arrays don't have a truth value at all, and not cannot be applied to them.

    If you want to test whether an object is None, the most general, reliable way is to literally use an is check against None:

    if a is None:
        ...
    else:
        ...
    

    This doesn't depend on objects having a truth value, so it works with NumPy arrays.

    Note that the test has to be is, not ==. is is an object identity test. == is whatever the arguments say it is, and NumPy arrays say it's a broadcasted elementwise equality comparison, producing a boolean array:

    >>> a = numpy.arange(5)
    >>> a == None
    array([False, False, False, False, False])
    >>> if a == None:
    ...     pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: The truth value of an array with more than one element is ambiguous.
     Use a.any() or a.all()
    

    On the other side of things, if you want to test whether an object is a NumPy array, you can test its type:

    # Careful - the type is np.ndarray, not np.array. np.array is a factory function.
    if type(a) is np.ndarray:
        ...
    else:
        ...
    

    You can also use isinstance, which will also return True for subclasses of that type (if that is what you want). Considering how terrible and incompatible np.matrix is, you may not actually want this:

    # Again, ndarray, not array, because array is a factory function.
    if isinstance(a, np.ndarray):
        ...
    else:
        ...    
    
    0 讨论(0)
  • 2020-12-07 17:51

    If you are trying to do something very similar: a is not None, the same issue comes up. That is, Numpy complains that one must use a.any or a.all.

    A workaround is to do:

    if not (a is None):
        pass
    

    Not too pretty, but it does the job.

    0 讨论(0)
  • 2020-12-07 17:52

    You can see if object has shape or not

    def check_array(x):
        try:
            x.shape
            return True
        except:
            return False
    
    0 讨论(0)
提交回复
热议问题