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:
print "please initialize a"
a = None
check_a(a)
a = np.array([1,2])
check_a(a)
But, this code raises ValueError. What is the straight forward way?
ValueError Traceback (most recent call last)
<ipython-input-41-0201c81c185e> in <module>()
6 check_a(a)
7 a = np.array([1,2])
----> 8 check_a(a)
<ipython-input-41-0201c81c185e> in check_a(a)
1 def check_a(a):
----> 2 if not a:
3 print "please initialize a"
4
5 a = None
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
ValueError
is one of the most commonnumpy
questions. It meansnot a
produces a boolean array, with (in this case) 2 values. This boolean array cannot be used as anif
condition! Theis None
alternative is good to know, but you should also understand this error. – hpaulj Apr 22 '16 at 5:01not
, so the error actually happens whennot
tries to treat the array as a single boolean and finds out it can't. If it had been~a
, that would have used NumPy's overload and failed whenif
tries to use the negated array as a single boolean. – user2357112 supports Monica Apr 19 at 22:41