Skip to content

Commit 8e4de94

Browse files
bwignallgouthambs
authored andcommitted
CLN: Change assert_([not] isinstance(a,b)) to specialized forms
Work on pandas-dev#6175. Changes instances of assert_([not] isinstance(a,b)) to specialized assert[Not]IsInstance(a, b).
1 parent c69f83b commit 8e4de94

15 files changed

+61
-47
lines changed

pandas/io/tests/test_packers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ def test_multi(self):
359359
l = [self.frame['float'], self.frame['float']
360360
.A, self.frame['float'].B, None]
361361
l_rec = self.encode_decode(l)
362-
self.assert_(isinstance(l_rec, tuple))
362+
self.assertIsInstance(l_rec, tuple)
363363
check_arbitrary(l, l_rec)
364364

365365
def test_iterator(self):

pandas/io/tests/test_parsers.py

+7-9
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ def test_multiple_date_cols_with_header(self):
415415
KORD,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000"""
416416

417417
df = self.read_csv(StringIO(data), parse_dates={'nominal': [1, 2]})
418-
self.assert_(not isinstance(df.nominal[0], compat.string_types))
418+
self.assertNotIsInstance(df.nominal[0], compat.string_types)
419419

420420
ts_data = """\
421421
ID,date,nominalTime,actualTime,A,B,C,D,E
@@ -1006,8 +1006,7 @@ def test_read_csv_dataframe(self):
10061006
parse_dates=True)
10071007
self.assert_numpy_array_equal(df.columns, ['A', 'B', 'C', 'D'])
10081008
self.assertEqual(df.index.name, 'index')
1009-
self.assert_(isinstance(df.index[0], (datetime, np.datetime64,
1010-
Timestamp)))
1009+
self.assertIsInstance(df.index[0], (datetime, np.datetime64, Timestamp))
10111010
self.assertEqual(df.values.dtype, np.float64)
10121011
tm.assert_frame_equal(df, df2)
10131012

@@ -1016,8 +1015,7 @@ def test_read_csv_no_index_name(self):
10161015
df2 = self.read_table(self.csv2, sep=',', index_col=0,
10171016
parse_dates=True)
10181017
self.assert_numpy_array_equal(df.columns, ['A', 'B', 'C', 'D', 'E'])
1019-
self.assert_(isinstance(df.index[0], (datetime, np.datetime64,
1020-
Timestamp)))
1018+
self.assertIsInstance(df.index[0], (datetime, np.datetime64, Timestamp))
10211019
self.assertEqual(df.ix[:, ['A', 'B', 'C', 'D']].values.dtype, np.float64)
10221020
tm.assert_frame_equal(df, df2)
10231021

@@ -1441,13 +1439,13 @@ def test_multi_index_parse_dates(self):
14411439
20090103,three,c,4,5
14421440
"""
14431441
df = self.read_csv(StringIO(data), index_col=[0, 1], parse_dates=True)
1444-
self.assert_(isinstance(df.index.levels[0][0],
1445-
(datetime, np.datetime64, Timestamp)))
1442+
self.assertIsInstance(df.index.levels[0][0],
1443+
(datetime, np.datetime64, Timestamp))
14461444

14471445
# specify columns out of order!
14481446
df2 = self.read_csv(StringIO(data), index_col=[1, 0], parse_dates=True)
1449-
self.assert_(isinstance(df2.index.levels[1][0],
1450-
(datetime, np.datetime64, Timestamp)))
1447+
self.assertIsInstance(df2.index.levels[1][0],
1448+
(datetime, np.datetime64, Timestamp))
14511449

14521450
def test_skip_footer(self):
14531451
data = """A,B,C

pandas/io/tests/test_pytables.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3554,7 +3554,7 @@ def f():
35543554
# valid
35553555
result = store.select_column('df', 'index')
35563556
tm.assert_almost_equal(result.values, Series(df.index).values)
3557-
self.assert_(isinstance(result,Series))
3557+
self.assertIsInstance(result,Series)
35583558

35593559
# not a data indexable column
35603560
self.assertRaises(
@@ -3622,7 +3622,7 @@ def test_coordinates(self):
36223622
result = store.select('df', where=c)
36233623
expected = df.ix[3:4, :]
36243624
tm.assert_frame_equal(result, expected)
3625-
self.assert_(isinstance(c, Index))
3625+
self.assertIsInstance(c, Index)
36263626

36273627
# multiple tables
36283628
_maybe_remove(store, 'df1')

pandas/io/tests/test_stata.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -277,11 +277,11 @@ def test_encoding(self):
277277
if compat.PY3:
278278
expected = raw.kreis1849[0]
279279
self.assertEqual(result, expected)
280-
self.assert_(isinstance(result, compat.string_types))
280+
self.assertIsInstance(result, compat.string_types)
281281
else:
282282
expected = raw.kreis1849.str.decode("latin-1")[0]
283283
self.assertEqual(result, expected)
284-
self.assert_(isinstance(result, unicode))
284+
self.assertIsInstance(result, unicode)
285285

286286
def test_read_write_dta11(self):
287287
# skip_if_not_little_endian()

pandas/sparse/tests/test_sparse.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,7 @@ def _compare_with_dense(sp):
405405
def _compare(idx):
406406
dense_result = dense.take(idx).values
407407
sparse_result = sp.take(idx)
408-
self.assert_(isinstance(sparse_result, SparseSeries))
408+
self.assertIsInstance(sparse_result, SparseSeries)
409409
assert_almost_equal(dense_result, sparse_result.values.values)
410410

411411
_compare([1., 2., 3., 4., 5., 0.])
@@ -652,7 +652,7 @@ def test_dropna(self):
652652

653653
result = self.bseries.dropna()
654654
expected = self.bseries.to_dense().dropna()
655-
self.assert_(not isinstance(result, SparseSeries))
655+
self.assertNotIsInstance(result, SparseSeries)
656656
tm.assert_series_equal(result, expected)
657657

658658
def test_homogenize(self):

pandas/tests/test_compat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
class TestBuiltinIterators(unittest.TestCase):
1515
def check_result(self, actual, expected, lengths):
1616
for (iter_res, list_res), exp, length in zip(actual, expected, lengths):
17-
self.assert_(not isinstance(iter_res, list))
17+
self.assertNotIsInstance(iter_res, list)
1818
tm.assert_isinstance(list_res, list)
1919
iter_res = list(iter_res)
2020
self.assertEqual(len(list_res), length)

pandas/tests/test_frame.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -10427,11 +10427,11 @@ def _check_stat_op(self, name, alternative, frame=None, has_skipna=True,
1042710427
df = DataFrame({'b': date_range('1/1/2001', periods=2)})
1042810428
_f = getattr(df, name)
1042910429
result = _f()
10430-
self.assert_(isinstance(result, Series))
10430+
self.assertIsInstance(result, Series)
1043110431

1043210432
df['a'] = lrange(len(df))
1043310433
result = getattr(df, name)()
10434-
self.assert_(isinstance(result, Series))
10434+
self.assertIsInstance(result, Series)
1043510435
self.assert_(len(result))
1043610436

1043710437
if has_skipna:

pandas/tests/test_graphics.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -469,13 +469,13 @@ def test_xcompat(self):
469469
df = tm.makeTimeDataFrame()
470470
ax = df.plot(x_compat=True)
471471
lines = ax.get_lines()
472-
self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
472+
self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex)
473473

474474
tm.close()
475475
pd.plot_params['xaxis.compat'] = True
476476
ax = df.plot()
477477
lines = ax.get_lines()
478-
self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
478+
self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex)
479479

480480
tm.close()
481481
pd.plot_params['x_compat'] = False
@@ -488,7 +488,7 @@ def test_xcompat(self):
488488
with pd.plot_params.use('x_compat', True):
489489
ax = df.plot()
490490
lines = ax.get_lines()
491-
self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
491+
self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex)
492492

493493
tm.close()
494494
ax = df.plot()

pandas/tests/test_index.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ def _check(op):
295295
index_result = op(index, element)
296296

297297
tm.assert_isinstance(index_result, np.ndarray)
298-
self.assert_(not isinstance(index_result, Index))
298+
self.assertNotIsInstance(index_result, Index)
299299
self.assert_numpy_array_equal(arr_result, index_result)
300300

301301
_check(operator.eq)
@@ -762,7 +762,7 @@ def test_boolean_cmp(self):
762762

763763
self.assert_(res.all())
764764
self.assertEqual(res.dtype, 'bool')
765-
self.assert_(not isinstance(res, Index))
765+
self.assertNotIsInstance(res, Index)
766766

767767
def test_get_level_values(self):
768768
result = self.strIndex.get_level_values(0)
@@ -808,35 +808,36 @@ def test_repr_roundtrip(self):
808808
tm.assert_index_equal(eval(repr(ind)), ind)
809809

810810
def check_is_index(self, i):
811-
self.assert_(isinstance(i, Index) and not isinstance(i, Float64Index))
811+
self.assertIsInstance(i, Index)
812+
self.assertNotIsInstance(i, Float64Index)
812813

813814
def check_coerce(self, a, b, is_float_index=True):
814815
self.assert_(a.equals(b))
815816
if is_float_index:
816-
self.assert_(isinstance(b, Float64Index))
817+
self.assertIsInstance(b, Float64Index)
817818
else:
818819
self.check_is_index(b)
819820

820821
def test_constructor(self):
821822

822823
# explicit construction
823824
index = Float64Index([1,2,3,4,5])
824-
self.assert_(isinstance(index, Float64Index))
825+
self.assertIsInstance(index, Float64Index)
825826
self.assert_((index.values == np.array([1,2,3,4,5],dtype='float64')).all())
826827
index = Float64Index(np.array([1,2,3,4,5]))
827-
self.assert_(isinstance(index, Float64Index))
828+
self.assertIsInstance(index, Float64Index)
828829
index = Float64Index([1.,2,3,4,5])
829-
self.assert_(isinstance(index, Float64Index))
830+
self.assertIsInstance(index, Float64Index)
830831
index = Float64Index(np.array([1.,2,3,4,5]))
831-
self.assert_(isinstance(index, Float64Index))
832+
self.assertIsInstance(index, Float64Index)
832833
self.assertEqual(index.dtype, object)
833834

834835
index = Float64Index(np.array([1.,2,3,4,5]),dtype=np.float32)
835-
self.assert_(isinstance(index, Float64Index))
836+
self.assertIsInstance(index, Float64Index)
836837
self.assertEqual(index.dtype, object)
837838

838839
index = Float64Index(np.array([1,2,3,4,5]),dtype=np.float32)
839-
self.assert_(isinstance(index, Float64Index))
840+
self.assertIsInstance(index, Float64Index)
840841
self.assertEqual(index.dtype, object)
841842

842843
# nan handling
@@ -1548,7 +1549,7 @@ def test_constructor_single_level(self):
15481549
labels=[[0, 1, 2, 3]],
15491550
names=['first'])
15501551
tm.assert_isinstance(single_level, Index)
1551-
self.assert_(not isinstance(single_level, MultiIndex))
1552+
self.assertNotIsInstance(single_level, MultiIndex)
15521553
self.assertEqual(single_level.name, 'first')
15531554

15541555
single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],

pandas/tests/test_internals.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ def test_sparse(self):
378378
def test_sparse_mixed(self):
379379
mgr = create_blockmanager([get_sparse_ex1(),get_sparse_ex2(),get_float_ex()])
380380
self.assertEqual(len(mgr.blocks), 3)
381-
self.assert_(isinstance(mgr,BlockManager))
381+
self.assertIsInstance(mgr, BlockManager)
382382

383383
# what to test here?
384384

pandas/tests/test_multilevel.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def test_dataframe_constructor(self):
7575
index=[np.array(['a', 'a', 'b', 'b']),
7676
np.array(['x', 'y', 'x', 'y'])])
7777
tm.assert_isinstance(multi.index, MultiIndex)
78-
self.assert_(not isinstance(multi.columns, MultiIndex))
78+
self.assertNotIsInstance(multi.columns, MultiIndex)
7979

8080
multi = DataFrame(np.random.randn(4, 4),
8181
columns=[['a', 'a', 'b', 'b'],

pandas/tests/test_series.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ def test_scalar_conversion(self):
343343

344344
# Pass in scalar is disabled
345345
scalar = Series(0.5)
346-
self.assert_(not isinstance(scalar, float))
346+
self.assertNotIsInstance(scalar, float)
347347

348348
# coercion
349349
self.assertEqual(float(Series([1.])), 1.0)
@@ -1175,10 +1175,10 @@ def test_reshape_non_2d(self):
11751175
def test_reshape_2d_return_array(self):
11761176
x = Series(np.random.random(201), name='x')
11771177
result = x.reshape((-1, 1))
1178-
self.assert_(not isinstance(result, Series))
1178+
self.assertNotIsInstance(result, Series)
11791179

11801180
result2 = np.reshape(x, (-1, 1))
1181-
self.assert_(not isinstance(result, Series))
1181+
self.assertNotIsInstance(result, Series)
11821182

11831183
result = x[:, None]
11841184
expected = x.reshape((-1, 1))
@@ -2091,7 +2091,7 @@ def test_round(self):
20912091
def test_prod_numpy16_bug(self):
20922092
s = Series([1., 1., 1.], index=lrange(3))
20932093
result = s.prod()
2094-
self.assert_(not isinstance(result, Series))
2094+
self.assertNotIsInstance(result, Series)
20952095

20962096
def test_quantile(self):
20972097
from pandas.compat.scipy import scoreatpercentile
@@ -5722,7 +5722,7 @@ def test_timeseries_coercion(self):
57225722
idx = tm.makeDateIndex(10000)
57235723
ser = Series(np.random.randn(len(idx)), idx.astype(object))
57245724
self.assertTrue(ser.is_time_series)
5725-
self.assert_(isinstance(ser.index, DatetimeIndex))
5725+
self.assertIsInstance(ser.index, DatetimeIndex)
57265726

57275727
def test_replace(self):
57285728
N = 100

pandas/tseries/tests/test_offsets.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def test_apply_out_of_range(self):
107107
offset = self._offset(10000)
108108

109109
result = Timestamp('20080101') + offset
110-
self.assert_(isinstance(result, datetime))
110+
self.assertIsInstance(result, datetime)
111111
except (OutOfBoundsDatetime):
112112
raise
113113
except (ValueError, KeyError):

pandas/tseries/tests/test_timeseries.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -2042,7 +2042,7 @@ def test_insert(self):
20422042
result = idx.insert(1, 'inserted')
20432043
expected = Index([datetime(2000, 1, 4), 'inserted', datetime(2000, 1, 1),
20442044
datetime(2000, 1, 2)])
2045-
self.assert_(not isinstance(result, DatetimeIndex))
2045+
self.assertNotIsInstance(result, DatetimeIndex)
20462046
tm.assert_index_equal(result, expected)
20472047

20482048
idx = date_range('1/1/2000', periods=3, freq='M')
@@ -3321,7 +3321,7 @@ def test_1700(self):
33213321
r2 = date_range(start=Timestamp('1710-10-01'),
33223322
periods=5,
33233323
freq='D').to_julian_date()
3324-
self.assert_(isinstance(r2, Float64Index))
3324+
self.assertIsInstance(r2, Float64Index)
33253325
tm.assert_index_equal(r1, r2)
33263326

33273327
def test_2000(self):
@@ -3333,7 +3333,7 @@ def test_2000(self):
33333333
r2 = date_range(start=Timestamp('2000-02-27'),
33343334
periods=5,
33353335
freq='D').to_julian_date()
3336-
self.assert_(isinstance(r2, Float64Index))
3336+
self.assertIsInstance(r2, Float64Index)
33373337
tm.assert_index_equal(r1, r2)
33383338

33393339
def test_hour(self):
@@ -3345,7 +3345,7 @@ def test_hour(self):
33453345
r2 = date_range(start=Timestamp('2000-02-27'),
33463346
periods=5,
33473347
freq='H').to_julian_date()
3348-
self.assert_(isinstance(r2, Float64Index))
3348+
self.assertIsInstance(r2, Float64Index)
33493349
tm.assert_index_equal(r1, r2)
33503350

33513351
def test_minute(self):
@@ -3357,7 +3357,7 @@ def test_minute(self):
33573357
r2 = date_range(start=Timestamp('2000-02-27'),
33583358
periods=5,
33593359
freq='T').to_julian_date()
3360-
self.assert_(isinstance(r2, Float64Index))
3360+
self.assertIsInstance(r2, Float64Index)
33613361
tm.assert_index_equal(r1, r2)
33623362

33633363
def test_second(self):
@@ -3369,7 +3369,7 @@ def test_second(self):
33693369
r2 = date_range(start=Timestamp('2000-02-27'),
33703370
periods=5,
33713371
freq='S').to_julian_date()
3372-
self.assert_(isinstance(r2, Float64Index))
3372+
self.assertIsInstance(r2, Float64Index)
33733373
tm.assert_index_equal(r1, r2)
33743374

33753375
if __name__ == '__main__':

pandas/util/testing.py

+15
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,21 @@ def assertNotIn(self, first, second, msg=''):
9999
a, b = first, second
100100
assert a not in b, "%s: %r is in %r" % (msg.format(a,b), a, b)
101101

102+
def assertIsInstance(self, obj, cls, msg=''):
103+
"""Test that obj is an instance of cls
104+
(which can be a class or a tuple of classes,
105+
as supported by isinstance())."""
106+
assert isinstance(obj, cls), (
107+
"%sExpected object to be of type %r, found %r instead" % (
108+
msg, cls, type(obj)))
109+
110+
def assertNotIsInstance(self, obj, cls, msg=''):
111+
"""Test that obj is not an instance of cls
112+
(which can be a class or a tuple of classes,
113+
as supported by isinstance())."""
114+
assert not isinstance(obj, cls), (
115+
"%sExpected object to be of type %r, found %r instead" % (
116+
msg, cls, type(obj)))
102117

103118
# NOTE: don't pass an NDFrame or index to this function - may not handle it
104119
# well.

0 commit comments

Comments
 (0)