As you can see in the sidebar this ValueError
has come up before - many times.
The core of the problem is that numpy arrays can return multiple truth values, while many Python operations expect just one.
I'll illustrate:
In [140]: this=None
In [141]: if this:print 'yes'
In [142]: if this is None: print 'yes'
yes
In [143]: this=np.array([1,2,3])
In [144]: if this: print 'yes'
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [145]: if this is None: print 'yes'
In [146]: this and this
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [147]: [1,2,3] is None
Out[147]: False
In [148]: this is None
Out[148]: False
In [149]: [1,2,3]==3 # one value
Out[149]: False
In [150]: this == 3 # multiple values
Out[150]: array([False, False, True], dtype=bool)
Logical operations like not
usually return a simple True/False, but for arrays, they return a value for each element of the array.
In [151]: not [1,2,3]
Out[151]: False
In [152]: not None
Out[152]: True
In [153]: not this
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In your function, if you don't give f
2 or more arguments, this
and that
will have value None
. The safe way to test that is with is None
or is not None
:
def f(some_stuff, this=None, that=None):
...do something...
if this is not None and that is not None:
perform_the_task()