Skip to content

CLN: Change assert_([not] isinstance(a,b)) to specialized forms #6577

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pandas/io/tests/test_packers.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ def test_multi(self):
l = [self.frame['float'], self.frame['float']
.A, self.frame['float'].B, None]
l_rec = self.encode_decode(l)
self.assert_(isinstance(l_rec, tuple))
self.assertIsInstance(l_rec, tuple)
check_arbitrary(l, l_rec)

def test_iterator(self):
Expand Down
16 changes: 7 additions & 9 deletions pandas/io/tests/test_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ def test_multiple_date_cols_with_header(self):
KORD,19990127, 23:00:00, 22:56:00, -0.5900, 1.7100, 4.6000, 0.0000, 280.0000"""

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

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

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

Expand Down Expand Up @@ -1441,13 +1439,13 @@ def test_multi_index_parse_dates(self):
20090103,three,c,4,5
"""
df = self.read_csv(StringIO(data), index_col=[0, 1], parse_dates=True)
self.assert_(isinstance(df.index.levels[0][0],
(datetime, np.datetime64, Timestamp)))
self.assertIsInstance(df.index.levels[0][0],
(datetime, np.datetime64, Timestamp))

# specify columns out of order!
df2 = self.read_csv(StringIO(data), index_col=[1, 0], parse_dates=True)
self.assert_(isinstance(df2.index.levels[1][0],
(datetime, np.datetime64, Timestamp)))
self.assertIsInstance(df2.index.levels[1][0],
(datetime, np.datetime64, Timestamp))

def test_skip_footer(self):
data = """A,B,C
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/tests/test_pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -3554,7 +3554,7 @@ def f():
# valid
result = store.select_column('df', 'index')
tm.assert_almost_equal(result.values, Series(df.index).values)
self.assert_(isinstance(result,Series))
self.assertIsInstance(result,Series)

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

# multiple tables
_maybe_remove(store, 'df1')
Expand Down
4 changes: 2 additions & 2 deletions pandas/io/tests/test_stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,11 +277,11 @@ def test_encoding(self):
if compat.PY3:
expected = raw.kreis1849[0]
self.assertEqual(result, expected)
self.assert_(isinstance(result, compat.string_types))
self.assertIsInstance(result, compat.string_types)
else:
expected = raw.kreis1849.str.decode("latin-1")[0]
self.assertEqual(result, expected)
self.assert_(isinstance(result, unicode))
self.assertIsInstance(result, unicode)

def test_read_write_dta11(self):
# skip_if_not_little_endian()
Expand Down
4 changes: 2 additions & 2 deletions pandas/sparse/tests/test_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ def _compare_with_dense(sp):
def _compare(idx):
dense_result = dense.take(idx).values
sparse_result = sp.take(idx)
self.assert_(isinstance(sparse_result, SparseSeries))
self.assertIsInstance(sparse_result, SparseSeries)
assert_almost_equal(dense_result, sparse_result.values.values)

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

result = self.bseries.dropna()
expected = self.bseries.to_dense().dropna()
self.assert_(not isinstance(result, SparseSeries))
self.assertNotIsInstance(result, SparseSeries)
tm.assert_series_equal(result, expected)

def test_homogenize(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
import nose
import pandas.util.testing as tm

class TestBuiltinIterators(unittest.TestCase):
class TestBuiltinIterators(tm.TestCase):
def check_result(self, actual, expected, lengths):
for (iter_res, list_res), exp, length in zip(actual, expected, lengths):
self.assert_(not isinstance(iter_res, list))
self.assertNotIsInstance(iter_res, list)
tm.assert_isinstance(list_res, list)
iter_res = list(iter_res)
self.assertEqual(len(list_res), length)
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -10427,11 +10427,11 @@ def _check_stat_op(self, name, alternative, frame=None, has_skipna=True,
df = DataFrame({'b': date_range('1/1/2001', periods=2)})
_f = getattr(df, name)
result = _f()
self.assert_(isinstance(result, Series))
self.assertIsInstance(result, Series)

df['a'] = lrange(len(df))
result = getattr(df, name)()
self.assert_(isinstance(result, Series))
self.assertIsInstance(result, Series)
self.assert_(len(result))

if has_skipna:
Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/test_graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,13 +469,13 @@ def test_xcompat(self):
df = tm.makeTimeDataFrame()
ax = df.plot(x_compat=True)
lines = ax.get_lines()
self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex)

tm.close()
pd.plot_params['xaxis.compat'] = True
ax = df.plot()
lines = ax.get_lines()
self.assert_(not isinstance(lines[0].get_xdata(), PeriodIndex))
self.assertNotIsInstance(lines[0].get_xdata(), PeriodIndex)

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

tm.close()
ax = df.plot()
Expand Down
23 changes: 12 additions & 11 deletions pandas/tests/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def _check(op):
index_result = op(index, element)

tm.assert_isinstance(index_result, np.ndarray)
self.assert_(not isinstance(index_result, Index))
self.assertNotIsInstance(index_result, Index)
self.assert_numpy_array_equal(arr_result, index_result)

_check(operator.eq)
Expand Down Expand Up @@ -762,7 +762,7 @@ def test_boolean_cmp(self):

self.assert_(res.all())
self.assertEqual(res.dtype, 'bool')
self.assert_(not isinstance(res, Index))
self.assertNotIsInstance(res, Index)

def test_get_level_values(self):
result = self.strIndex.get_level_values(0)
Expand Down Expand Up @@ -808,35 +808,36 @@ def test_repr_roundtrip(self):
tm.assert_index_equal(eval(repr(ind)), ind)

def check_is_index(self, i):
self.assert_(isinstance(i, Index) and not isinstance(i, Float64Index))
self.assertIsInstance(i, Index)
self.assertNotIsInstance(i, Float64Index)

def check_coerce(self, a, b, is_float_index=True):
self.assert_(a.equals(b))
if is_float_index:
self.assert_(isinstance(b, Float64Index))
self.assertIsInstance(b, Float64Index)
else:
self.check_is_index(b)

def test_constructor(self):

# explicit construction
index = Float64Index([1,2,3,4,5])
self.assert_(isinstance(index, Float64Index))
self.assertIsInstance(index, Float64Index)
self.assert_((index.values == np.array([1,2,3,4,5],dtype='float64')).all())
index = Float64Index(np.array([1,2,3,4,5]))
self.assert_(isinstance(index, Float64Index))
self.assertIsInstance(index, Float64Index)
index = Float64Index([1.,2,3,4,5])
self.assert_(isinstance(index, Float64Index))
self.assertIsInstance(index, Float64Index)
index = Float64Index(np.array([1.,2,3,4,5]))
self.assert_(isinstance(index, Float64Index))
self.assertIsInstance(index, Float64Index)
self.assertEqual(index.dtype, object)

index = Float64Index(np.array([1.,2,3,4,5]),dtype=np.float32)
self.assert_(isinstance(index, Float64Index))
self.assertIsInstance(index, Float64Index)
self.assertEqual(index.dtype, object)

index = Float64Index(np.array([1,2,3,4,5]),dtype=np.float32)
self.assert_(isinstance(index, Float64Index))
self.assertIsInstance(index, Float64Index)
self.assertEqual(index.dtype, object)

# nan handling
Expand Down Expand Up @@ -1548,7 +1549,7 @@ def test_constructor_single_level(self):
labels=[[0, 1, 2, 3]],
names=['first'])
tm.assert_isinstance(single_level, Index)
self.assert_(not isinstance(single_level, MultiIndex))
self.assertNotIsInstance(single_level, MultiIndex)
self.assertEqual(single_level.name, 'first')

single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/test_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ def test_sparse(self):
def test_sparse_mixed(self):
mgr = create_blockmanager([get_sparse_ex1(),get_sparse_ex2(),get_float_ex()])
self.assertEqual(len(mgr.blocks), 3)
self.assert_(isinstance(mgr,BlockManager))
self.assertIsInstance(mgr, BlockManager)

# what to test here?

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/test_multilevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def test_dataframe_constructor(self):
index=[np.array(['a', 'a', 'b', 'b']),
np.array(['x', 'y', 'x', 'y'])])
tm.assert_isinstance(multi.index, MultiIndex)
self.assert_(not isinstance(multi.columns, MultiIndex))
self.assertNotIsInstance(multi.columns, MultiIndex)

multi = DataFrame(np.random.randn(4, 4),
columns=[['a', 'a', 'b', 'b'],
Expand Down
10 changes: 5 additions & 5 deletions pandas/tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ def test_scalar_conversion(self):

# Pass in scalar is disabled
scalar = Series(0.5)
self.assert_(not isinstance(scalar, float))
self.assertNotIsInstance(scalar, float)

# coercion
self.assertEqual(float(Series([1.])), 1.0)
Expand Down Expand Up @@ -1175,10 +1175,10 @@ def test_reshape_non_2d(self):
def test_reshape_2d_return_array(self):
x = Series(np.random.random(201), name='x')
result = x.reshape((-1, 1))
self.assert_(not isinstance(result, Series))
self.assertNotIsInstance(result, Series)

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

result = x[:, None]
expected = x.reshape((-1, 1))
Expand Down Expand Up @@ -2091,7 +2091,7 @@ def test_round(self):
def test_prod_numpy16_bug(self):
s = Series([1., 1., 1.], index=lrange(3))
result = s.prod()
self.assert_(not isinstance(result, Series))
self.assertNotIsInstance(result, Series)

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

def test_replace(self):
N = 100
Expand Down
2 changes: 1 addition & 1 deletion pandas/tseries/tests/test_offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def test_apply_out_of_range(self):
offset = self._offset(10000)

result = Timestamp('20080101') + offset
self.assert_(isinstance(result, datetime))
self.assertIsInstance(result, datetime)
except (OutOfBoundsDatetime):
raise
except (ValueError, KeyError):
Expand Down
12 changes: 6 additions & 6 deletions pandas/tseries/tests/test_timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -2042,7 +2042,7 @@ def test_insert(self):
result = idx.insert(1, 'inserted')
expected = Index([datetime(2000, 1, 4), 'inserted', datetime(2000, 1, 1),
datetime(2000, 1, 2)])
self.assert_(not isinstance(result, DatetimeIndex))
self.assertNotIsInstance(result, DatetimeIndex)
tm.assert_index_equal(result, expected)

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

def test_2000(self):
Expand All @@ -3333,7 +3333,7 @@ def test_2000(self):
r2 = date_range(start=Timestamp('2000-02-27'),
periods=5,
freq='D').to_julian_date()
self.assert_(isinstance(r2, Float64Index))
self.assertIsInstance(r2, Float64Index)
tm.assert_index_equal(r1, r2)

def test_hour(self):
Expand All @@ -3345,7 +3345,7 @@ def test_hour(self):
r2 = date_range(start=Timestamp('2000-02-27'),
periods=5,
freq='H').to_julian_date()
self.assert_(isinstance(r2, Float64Index))
self.assertIsInstance(r2, Float64Index)
tm.assert_index_equal(r1, r2)

def test_minute(self):
Expand All @@ -3357,7 +3357,7 @@ def test_minute(self):
r2 = date_range(start=Timestamp('2000-02-27'),
periods=5,
freq='T').to_julian_date()
self.assert_(isinstance(r2, Float64Index))
self.assertIsInstance(r2, Float64Index)
tm.assert_index_equal(r1, r2)

def test_second(self):
Expand All @@ -3369,7 +3369,7 @@ def test_second(self):
r2 = date_range(start=Timestamp('2000-02-27'),
periods=5,
freq='S').to_julian_date()
self.assert_(isinstance(r2, Float64Index))
self.assertIsInstance(r2, Float64Index)
tm.assert_index_equal(r1, r2)

if __name__ == '__main__':
Expand Down
15 changes: 15 additions & 0 deletions pandas/util/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ def assertNotIn(self, first, second, msg=''):
a, b = first, second
assert a not in b, "%s: %r is in %r" % (msg.format(a,b), a, b)

def assertIsInstance(self, obj, cls, msg=''):
"""Test that obj is an instance of cls
(which can be a class or a tuple of classes,
as supported by isinstance())."""
assert isinstance(obj, cls), (
"%sExpected object to be of type %r, found %r instead" % (
msg, cls, type(obj)))

def assertNotIsInstance(self, obj, cls, msg=''):
"""Test that obj is not an instance of cls
(which can be a class or a tuple of classes,
as supported by isinstance())."""
assert not isinstance(obj, cls), (
"%sExpected object to be of type %r, found %r instead" % (
msg, cls, type(obj)))

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