rkjt50r983 rkjt50r983 - 1 year ago 249
Python Question

check if variable is None or numpy.array in python

I'd like to check if variable is None or numpy.array. I've implemented

function to do this.

def check_a(a):
if not a:
print "please initialize a"

a = None
a = np.array([1,2])

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"
5 a = None

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

Answer Source

Just do it!

if a is None:

Or if you want to be more explicit:

if type(a) is np.array:

Thanks to @farenorth, there is also another solution: isinstance. This is the same as above, but will also return True for subclasses of that type (if that is what you want).

if isinstance(a, np.array):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download