Skip to content

Commit 464dd3d

Browse files
author
y-p
committed
Merge pull request #3023 from y-p/no_asserts
Continuing #2057, s/assert/raise AssertionError/g
2 parents f4e218c + 6bdcd22 commit 464dd3d

19 files changed

+115
-57
lines changed

pandas/core/config.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -313,8 +313,10 @@ def __doc__(self):
313313

314314
class option_context(object):
315315
def __init__(self, *args):
316-
assert len(args) % 2 == 0 and len(args) >= 2, \
317-
"Need to invoke as option_context(pat,val,[(pat,val),..))."
316+
if not ( len(args) % 2 == 0 and len(args) >= 2):
317+
errmsg = "Need to invoke as option_context(pat,val,[(pat,val),..))."
318+
raise AssertionError(errmsg)
319+
318320
ops = zip(args[::2], args[1::2])
319321
undo = []
320322
for pat, val in ops:

pandas/core/frame.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -709,7 +709,8 @@ def __unicode__(self):
709709
self.info(buf=buf, verbose=verbose)
710710

711711
value = buf.getvalue()
712-
assert type(value) == unicode
712+
if not type(value) == unicode:
713+
raise AssertionError()
713714

714715
return value
715716

pandas/core/panel.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,8 @@ def get_value(self, *args):
618618
value : scalar value
619619
"""
620620
# require an arg for each axis
621-
assert(len(args) == self._AXIS_LEN)
621+
if not ((len(args) == self._AXIS_LEN)):
622+
raise AssertionError()
622623

623624
# hm, two layers to the onion
624625
frame = self._get_item_cache(args[0])
@@ -642,7 +643,8 @@ def set_value(self, *args):
642643
otherwise a new object
643644
"""
644645
# require an arg for each axis and the value
645-
assert(len(args) == self._AXIS_LEN + 1)
646+
if not ((len(args) == self._AXIS_LEN + 1)):
647+
raise AssertionError()
646648

647649
try:
648650
frame = self._get_item_cache(args[0])
@@ -685,7 +687,8 @@ def __setitem__(self, key, value):
685687
**self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:]))
686688
mat = value.values
687689
elif isinstance(value, np.ndarray):
688-
assert(value.shape == shape[1:])
690+
if not ((value.shape == shape[1:])):
691+
raise AssertionError()
689692
mat = np.asarray(value)
690693
elif np.isscalar(value):
691694
dtype, value = _infer_dtype_from_scalar(value)
@@ -1481,7 +1484,8 @@ def _prep_ndarray(self, values, copy=True):
14811484
else:
14821485
if copy:
14831486
values = values.copy()
1484-
assert(values.ndim == self._AXIS_LEN)
1487+
if not ((values.ndim == self._AXIS_LEN)):
1488+
raise AssertionError()
14851489
return values
14861490

14871491
@staticmethod

pandas/core/series.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -1126,7 +1126,8 @@ def __unicode__(self):
11261126
else:
11271127
result = u'Series([], dtype: %s)' % self.dtype
11281128

1129-
assert type(result) == unicode
1129+
if not ( type(result) == unicode):
1130+
raise AssertionError()
11301131
return result
11311132

11321133
def __repr__(self):
@@ -1194,7 +1195,9 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None,
11941195
the_repr = self._get_repr(float_format=float_format, na_rep=na_rep,
11951196
length=length, dtype=dtype, name=name)
11961197

1197-
assert type(the_repr) == unicode
1198+
# catch contract violations
1199+
if not type(the_repr) == unicode:
1200+
raise AssertionError("expected unicode string")
11981201

11991202
if buf is None:
12001203
return the_repr
@@ -1212,7 +1215,8 @@ def _get_repr(self, name=False, print_header=False, length=True, dtype=True,
12121215
length=length, dtype=dtype, na_rep=na_rep,
12131216
float_format=float_format)
12141217
result = formatter.to_string()
1215-
assert type(result) == unicode
1218+
if not ( type(result) == unicode):
1219+
raise AssertionError()
12161220
return result
12171221

12181222
def __iter__(self):

pandas/io/date_converters.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,12 @@ def _maybe_cast(arr):
4646

4747

4848
def _check_columns(cols):
49-
assert(len(cols) > 0)
49+
if not ((len(cols) > 0)):
50+
raise AssertionError()
5051

5152
N = len(cols[0])
5253
for c in cols[1:]:
53-
assert(len(c) == N)
54+
if not ((len(c) == N)):
55+
raise AssertionError()
5456

5557
return N

pandas/io/parsers.py

+12-7
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,8 @@ def _clean_options(self, options, engine):
579579

580580
# type conversion-related
581581
if converters is not None:
582-
assert(isinstance(converters, dict))
582+
if not (isinstance(converters, dict)):
583+
raise AssertionError()
583584
else:
584585
converters = {}
585586

@@ -1474,7 +1475,8 @@ def _rows_to_cols(self, content):
14741475
if self._implicit_index:
14751476
col_len += len(self.index_col)
14761477

1477-
assert(self.skip_footer >= 0)
1478+
if not ((self.skip_footer >= 0)):
1479+
raise AssertionError()
14781480

14791481
if col_len != zip_len and self.index_col is not False:
14801482
row_num = -1
@@ -1768,12 +1770,15 @@ def __init__(self, f, colspecs, filler, thousands=None):
17681770
self.filler = filler # Empty characters between fields.
17691771
self.thousands = thousands
17701772

1771-
assert isinstance(colspecs, (tuple, list))
1773+
if not ( isinstance(colspecs, (tuple, list))):
1774+
raise AssertionError()
1775+
17721776
for colspec in colspecs:
1773-
assert isinstance(colspec, (tuple, list))
1774-
assert len(colspec) == 2
1775-
assert isinstance(colspec[0], int)
1776-
assert isinstance(colspec[1], int)
1777+
if not ( isinstance(colspec, (tuple, list)) and
1778+
len(colspec) == 2 and
1779+
isinstance(colspec[0], int) and
1780+
isinstance(colspec[1], int) ):
1781+
raise AssertionError()
17771782

17781783
def next(self):
17791784
line = next(self.f)

pandas/sparse/array.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ def _sparse_op_wrap(op, name):
2525
"""
2626
def wrapper(self, other):
2727
if isinstance(other, np.ndarray):
28-
assert(len(self) == len(other))
28+
if not ((len(self) == len(other))):
29+
raise AssertionError()
2930
if not isinstance(other, SparseArray):
3031
other = SparseArray(other, fill_value=self.fill_value)
3132
return _sparse_array_op(self, other, op, name)
@@ -129,7 +130,8 @@ def __new__(cls, data, sparse_index=None, kind='integer', fill_value=None,
129130
fill_value=fill_value)
130131
else:
131132
values = data
132-
assert(len(values) == sparse_index.npoints)
133+
if not ((len(values) == sparse_index.npoints)):
134+
raise AssertionError()
133135

134136
# Create array, do *not* copy data by default
135137
if copy:
@@ -275,7 +277,8 @@ def take(self, indices, axis=0):
275277
-------
276278
taken : ndarray
277279
"""
278-
assert(axis == 0)
280+
if not ((axis == 0)):
281+
raise AssertionError()
279282
indices = np.asarray(indices, dtype=int)
280283

281284
n = len(self)

pandas/sparse/frame.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -709,7 +709,9 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='',
709709

710710
def _join_index(self, other, how, lsuffix, rsuffix):
711711
if isinstance(other, Series):
712-
assert(other.name is not None)
712+
if not (other.name is not None):
713+
raise AssertionError()
714+
713715
other = SparseDataFrame({other.name: other},
714716
default_fill_value=self.default_fill_value)
715717

pandas/sparse/panel.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ def __init__(self, frames, items=None, major_axis=None, minor_axis=None,
7171
default_kind=default_kind)
7272
frames = new_frames
7373

74-
assert(isinstance(frames, dict))
74+
if not (isinstance(frames, dict)):
75+
raise AssertionError()
7576

7677
self.default_fill_value = fill_value = default_fill_value
7778
self.default_kind = kind = default_kind

pandas/sparse/series.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ def __new__(cls, data, index=None, sparse_index=None, kind='block',
110110
if isinstance(data, SparseSeries) and index is None:
111111
index = data.index
112112
elif index is not None:
113-
assert(len(index) == len(data))
113+
if not (len(index) == len(data)):
114+
raise AssertionError()
114115

115116
sparse_index = data.sp_index
116117
values = np.asarray(data)
@@ -128,7 +129,8 @@ def __new__(cls, data, index=None, sparse_index=None, kind='block',
128129
fill_value=fill_value)
129130
else:
130131
values = data
131-
assert(len(values) == sparse_index.npoints)
132+
if not (len(values) == sparse_index.npoints):
133+
raise AssertionError()
132134
else:
133135
if index is None:
134136
raise Exception('must pass index!')
@@ -446,7 +448,8 @@ def sparse_reindex(self, new_index):
446448
-------
447449
reindexed : SparseSeries
448450
"""
449-
assert(isinstance(new_index, splib.SparseIndex))
451+
if not (isinstance(new_index, splib.SparseIndex)):
452+
raise AssertionError()
450453

451454
new_values = self.sp_index.to_int_index().reindex(self.sp_values,
452455
self.fill_value,

pandas/stats/ols.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,8 @@ def _set_window(self, window_type, window, min_periods):
619619
self._window_type = scom._get_window_type(window_type)
620620

621621
if self._is_rolling:
622-
assert(window is not None)
622+
if not ((window is not None)):
623+
raise AssertionError()
623624
if min_periods is None:
624625
min_periods = window
625626
else:
@@ -1196,7 +1197,8 @@ def _nobs_raw(self):
11961197
return result.astype(int)
11971198

11981199
def _beta_matrix(self, lag=0):
1199-
assert(lag >= 0)
1200+
if not ((lag >= 0)):
1201+
raise AssertionError()
12001202

12011203
betas = self._beta_raw
12021204

@@ -1257,7 +1259,8 @@ def _filter_data(lhs, rhs, weights=None):
12571259
Cleaned lhs and rhs
12581260
"""
12591261
if not isinstance(lhs, Series):
1260-
assert(len(lhs) == len(rhs))
1262+
if not ((len(lhs) == len(rhs))):
1263+
raise AssertionError()
12611264
lhs = Series(lhs, index=rhs.index)
12621265

12631266
rhs = _combine_rhs(rhs)

pandas/stats/plm.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,10 @@ def _prepare_data(self):
101101
y_regressor = y
102102

103103
if weights is not None:
104-
assert(y_regressor.index.equals(weights.index))
105-
assert(x_regressor.index.equals(weights.index))
104+
if not ((y_regressor.index.equals(weights.index))):
105+
raise AssertionError()
106+
if not ((x_regressor.index.equals(weights.index))):
107+
raise AssertionError()
106108

107109
rt_weights = np.sqrt(weights)
108110
y_regressor = y_regressor * rt_weights
@@ -169,7 +171,8 @@ def _convert_x(self, x):
169171
# .iteritems
170172
iteritems = getattr(x, 'iteritems', x.items)
171173
for key, df in iteritems():
172-
assert(isinstance(df, DataFrame))
174+
if not ((isinstance(df, DataFrame))):
175+
raise AssertionError()
173176

174177
if _is_numeric(df):
175178
x_converted[key] = df
@@ -637,7 +640,8 @@ def _y_predict_raw(self):
637640
return (betas * x).sum(1)
638641

639642
def _beta_matrix(self, lag=0):
640-
assert(lag >= 0)
643+
if not ((lag >= 0)):
644+
raise AssertionError()
641645

642646
index = self._y_trans.index
643647
major_labels = index.labels[0]

pandas/tools/merge.py

+19-10
Original file line numberDiff line numberDiff line change
@@ -404,14 +404,17 @@ def _validate_specification(self):
404404
elif self.left_on is not None:
405405
n = len(self.left_on)
406406
if self.right_index:
407-
assert(len(self.left_on) == self.right.index.nlevels)
407+
if not ((len(self.left_on) == self.right.index.nlevels)):
408+
raise AssertionError()
408409
self.right_on = [None] * n
409410
elif self.right_on is not None:
410411
n = len(self.right_on)
411412
if self.left_index:
412-
assert(len(self.right_on) == self.left.index.nlevels)
413+
if not ((len(self.right_on) == self.left.index.nlevels)):
414+
raise AssertionError()
413415
self.left_on = [None] * n
414-
assert(len(self.right_on) == len(self.left_on))
416+
if not ((len(self.right_on) == len(self.left_on))):
417+
raise AssertionError()
415418

416419

417420
def _get_join_indexers(left_keys, right_keys, sort=False, how='inner'):
@@ -424,7 +427,8 @@ def _get_join_indexers(left_keys, right_keys, sort=False, how='inner'):
424427
-------
425428
426429
"""
427-
assert(len(left_keys) == len(right_keys))
430+
if not ((len(left_keys) == len(right_keys))):
431+
raise AssertionError()
428432

429433
left_labels = []
430434
right_labels = []
@@ -537,8 +541,9 @@ def _left_join_on_index(left_ax, right_ax, join_keys, sort=False):
537541
left_indexer = None
538542

539543
if len(join_keys) > 1:
540-
assert(isinstance(right_ax, MultiIndex) and
541-
len(join_keys) == right_ax.nlevels)
544+
if not ((isinstance(right_ax, MultiIndex) and
545+
len(join_keys) == right_ax.nlevels) ):
546+
raise AssertionError()
542547

543548
left_tmp, right_indexer = \
544549
_get_multiindex_indexer(join_keys, right_ax,
@@ -637,7 +642,8 @@ def __init__(self, data_list, join_index, indexers, axis=1, copy=True):
637642
if axis <= 0: # pragma: no cover
638643
raise MergeError('Only axis >= 1 supported for this operation')
639644

640-
assert(len(data_list) == len(indexers))
645+
if not ((len(data_list) == len(indexers))):
646+
raise AssertionError()
641647

642648
self.units = []
643649
for data, indexer in zip(data_list, indexers):
@@ -925,7 +931,8 @@ def __init__(self, objs, axis=0, join='outer', join_axes=None,
925931
axis = 1 if axis == 0 else 0
926932

927933
self._is_series = isinstance(sample, Series)
928-
assert(0 <= axis <= sample.ndim)
934+
if not ((0 <= axis <= sample.ndim)):
935+
raise AssertionError()
929936

930937
# note: this is the BlockManager axis (since DataFrame is transposed)
931938
self.axis = axis
@@ -1084,7 +1091,8 @@ def _concat_single_item(self, objs, item):
10841091
to_concat.append(item_values)
10851092

10861093
# this method only gets called with axis >= 1
1087-
assert(self.axis >= 1)
1094+
if not ((self.axis >= 1)):
1095+
raise AssertionError()
10881096
return com._concat_compat(to_concat, axis=self.axis - 1)
10891097

10901098
def _get_result_dim(self):
@@ -1103,7 +1111,8 @@ def _get_new_axes(self):
11031111
continue
11041112
new_axes[i] = self._get_comb_axis(i)
11051113
else:
1106-
assert(len(self.join_axes) == ndim - 1)
1114+
if not ((len(self.join_axes) == ndim - 1)):
1115+
raise AssertionError()
11071116

11081117
# ufff...
11091118
indices = range(ndim)

pandas/tools/pivot.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,8 @@ def _get_names(arrs, names, prefix='row'):
300300
else:
301301
names.append('%s_%d' % (prefix, i))
302302
else:
303-
assert(len(names) == len(arrs))
303+
if not ((len(names) == len(arrs))):
304+
raise AssertionError()
304305
if not isinstance(names, list):
305306
names = list(names)
306307

0 commit comments

Comments
 (0)