Skip to content

Commit 1f64bc8

Browse files
committed
API: raise on __nonzero__ for Index (GH7897)
1 parent 24bb1a9 commit 1f64bc8

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

doc/source/v0.15.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ a transparent change with only very limited API implications (:issue:`5080`, :is
173173

174174
- you may need to unpickle pandas version < 0.15.0 pickles using ``pd.read_pickle`` rather than ``pickle.load``. See :ref:`pickle docs <io.pickle>`
175175
- when plotting with a ``PeriodIndex``. The ``matplotlib`` internal axes will now be arrays of ``Period`` rather than a ``PeriodIndex``. (this is similar to how a ``DatetimeIndex`` passes arrays of ``datetimes`` now)
176+
- MultiIndexes will now raise similary to other pandas objects w.r.t. truth testing, See :ref:`here <gotchas.truth>` (:issue:`7897`).
176177

177178
.. _whatsnew_0150.cat:
178179

pandas/core/index.py

+7
Original file line numberDiff line numberDiff line change
@@ -838,6 +838,13 @@ def __setstate__(self, state):
838838
def __deepcopy__(self, memo={}):
839839
return self.copy(deep=True)
840840

841+
def __nonzero__(self):
842+
raise ValueError("The truth value of a {0} is ambiguous. "
843+
"Use a.empty, a.bool(), a.item(), a.any() or a.all()."
844+
.format(self.__class__.__name__))
845+
846+
__bool__ = __nonzero__
847+
841848
def __contains__(self, key):
842849
hash(key)
843850
# work around some kind of odd cython bug

pandas/tests/test_index.py

+22
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,15 @@ def test_numeric_compat(self):
7474
"cannot perform floor division",
7575
lambda : 1 // idx)
7676

77+
def test_boolean_context_compat(self):
78+
79+
# boolean context compat
80+
idx = self.create_index()
81+
def f():
82+
if idx:
83+
pass
84+
tm.assertRaisesRegexp(ValueError,'The truth value of a',f)
85+
7786
class TestIndex(Base, tm.TestCase):
7887
_holder = Index
7988
_multiprocess_can_split_ = True
@@ -1656,6 +1665,19 @@ def setUp(self):
16561665
def create_index(self):
16571666
return self.index
16581667

1668+
def test_boolean_context_compat2(self):
1669+
1670+
# boolean context compat
1671+
# GH7897
1672+
i1 = MultiIndex.from_tuples([('A', 1), ('A', 2)])
1673+
i2 = MultiIndex.from_tuples([('A', 1), ('A', 3)])
1674+
common = i1.intersection(i2)
1675+
1676+
def f():
1677+
if common:
1678+
pass
1679+
tm.assertRaisesRegexp(ValueError,'The truth value of a',f)
1680+
16591681
def test_hash_error(self):
16601682
with tm.assertRaisesRegexp(TypeError,
16611683
"unhashable type: %r" %

0 commit comments

Comments
 (0)