From 6bdcd22d00097a179436421e428bfc8d79467ea6 Mon Sep 17 00:00:00 2001 From: y-p Date: Tue, 12 Mar 2013 17:16:07 +0200 Subject: [PATCH] CLN: eliminate assert in favor of AssertionError GH2057 PTF --- pandas/core/config.py | 6 ++++-- pandas/core/frame.py | 3 ++- pandas/core/panel.py | 12 ++++++++---- pandas/core/series.py | 10 +++++++--- pandas/io/date_converters.py | 6 ++++-- pandas/io/parsers.py | 19 ++++++++++++------- pandas/sparse/array.py | 9 ++++++--- pandas/sparse/frame.py | 4 +++- pandas/sparse/panel.py | 3 ++- pandas/sparse/series.py | 9 ++++++--- pandas/stats/ols.py | 9 ++++++--- pandas/stats/plm.py | 12 ++++++++---- pandas/tools/merge.py | 29 +++++++++++++++++++---------- pandas/tools/pivot.py | 3 ++- pandas/tseries/index.py | 11 ++++++++--- pandas/tseries/period.py | 10 +++++++--- pandas/tseries/resample.py | 9 ++++++--- pandas/tseries/tools.py | 3 ++- pandas/util/decorators.py | 5 +++-- 19 files changed, 115 insertions(+), 57 deletions(-) diff --git a/pandas/core/config.py b/pandas/core/config.py index 59d2772c857bd..2d62b807cf203 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -313,8 +313,10 @@ def __doc__(self): class option_context(object): def __init__(self, *args): - assert len(args) % 2 == 0 and len(args) >= 2, \ - "Need to invoke as option_context(pat,val,[(pat,val),..))." + if not ( len(args) % 2 == 0 and len(args) >= 2): + errmsg = "Need to invoke as option_context(pat,val,[(pat,val),..))." + raise AssertionError(errmsg) + ops = zip(args[::2], args[1::2]) undo = [] for pat, val in ops: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 6fd627f42e055..69e7e4178ecfd 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -709,7 +709,8 @@ def __unicode__(self): self.info(buf=buf, verbose=verbose) value = buf.getvalue() - assert type(value) == unicode + if not type(value) == unicode: + raise AssertionError() return value diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 4f346d2e1860e..38abfcf925363 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -618,7 +618,8 @@ def get_value(self, *args): value : scalar value """ # require an arg for each axis - assert(len(args) == self._AXIS_LEN) + if not ((len(args) == self._AXIS_LEN)): + raise AssertionError() # hm, two layers to the onion frame = self._get_item_cache(args[0]) @@ -642,7 +643,8 @@ def set_value(self, *args): otherwise a new object """ # require an arg for each axis and the value - assert(len(args) == self._AXIS_LEN + 1) + if not ((len(args) == self._AXIS_LEN + 1)): + raise AssertionError() try: frame = self._get_item_cache(args[0]) @@ -685,7 +687,8 @@ def __setitem__(self, key, value): **self._construct_axes_dict_for_slice(self._AXIS_ORDERS[1:])) mat = value.values elif isinstance(value, np.ndarray): - assert(value.shape == shape[1:]) + if not ((value.shape == shape[1:])): + raise AssertionError() mat = np.asarray(value) elif np.isscalar(value): dtype, value = _infer_dtype_from_scalar(value) @@ -1481,7 +1484,8 @@ def _prep_ndarray(self, values, copy=True): else: if copy: values = values.copy() - assert(values.ndim == self._AXIS_LEN) + if not ((values.ndim == self._AXIS_LEN)): + raise AssertionError() return values @staticmethod diff --git a/pandas/core/series.py b/pandas/core/series.py index a68234b5d6bc1..7d9303fa75acd 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1126,7 +1126,8 @@ def __unicode__(self): else: result = u'Series([], dtype: %s)' % self.dtype - assert type(result) == unicode + if not ( type(result) == unicode): + raise AssertionError() return result def __repr__(self): @@ -1194,7 +1195,9 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None, the_repr = self._get_repr(float_format=float_format, na_rep=na_rep, length=length, dtype=dtype, name=name) - assert type(the_repr) == unicode + # catch contract violations + if not type(the_repr) == unicode: + raise AssertionError("expected unicode string") if buf is None: return the_repr @@ -1212,7 +1215,8 @@ def _get_repr(self, name=False, print_header=False, length=True, dtype=True, length=length, dtype=dtype, na_rep=na_rep, float_format=float_format) result = formatter.to_string() - assert type(result) == unicode + if not ( type(result) == unicode): + raise AssertionError() return result def __iter__(self): diff --git a/pandas/io/date_converters.py b/pandas/io/date_converters.py index ce670eec7032f..c7a60d13f1778 100644 --- a/pandas/io/date_converters.py +++ b/pandas/io/date_converters.py @@ -46,10 +46,12 @@ def _maybe_cast(arr): def _check_columns(cols): - assert(len(cols) > 0) + if not ((len(cols) > 0)): + raise AssertionError() N = len(cols[0]) for c in cols[1:]: - assert(len(c) == N) + if not ((len(c) == N)): + raise AssertionError() return N diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 60798bacbc144..c479bffdb3ab1 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -579,7 +579,8 @@ def _clean_options(self, options, engine): # type conversion-related if converters is not None: - assert(isinstance(converters, dict)) + if not (isinstance(converters, dict)): + raise AssertionError() else: converters = {} @@ -1474,7 +1475,8 @@ def _rows_to_cols(self, content): if self._implicit_index: col_len += len(self.index_col) - assert(self.skip_footer >= 0) + if not ((self.skip_footer >= 0)): + raise AssertionError() if col_len != zip_len and self.index_col is not False: row_num = -1 @@ -1768,12 +1770,15 @@ def __init__(self, f, colspecs, filler, thousands=None): self.filler = filler # Empty characters between fields. self.thousands = thousands - assert isinstance(colspecs, (tuple, list)) + if not ( isinstance(colspecs, (tuple, list))): + raise AssertionError() + for colspec in colspecs: - assert isinstance(colspec, (tuple, list)) - assert len(colspec) == 2 - assert isinstance(colspec[0], int) - assert isinstance(colspec[1], int) + if not ( isinstance(colspec, (tuple, list)) and + len(colspec) == 2 and + isinstance(colspec[0], int) and + isinstance(colspec[1], int) ): + raise AssertionError() def next(self): line = next(self.f) diff --git a/pandas/sparse/array.py b/pandas/sparse/array.py index 777a58a0f6c49..035db279064a0 100644 --- a/pandas/sparse/array.py +++ b/pandas/sparse/array.py @@ -25,7 +25,8 @@ def _sparse_op_wrap(op, name): """ def wrapper(self, other): if isinstance(other, np.ndarray): - assert(len(self) == len(other)) + if not ((len(self) == len(other))): + raise AssertionError() if not isinstance(other, SparseArray): other = SparseArray(other, fill_value=self.fill_value) return _sparse_array_op(self, other, op, name) @@ -129,7 +130,8 @@ def __new__(cls, data, sparse_index=None, kind='integer', fill_value=None, fill_value=fill_value) else: values = data - assert(len(values) == sparse_index.npoints) + if not ((len(values) == sparse_index.npoints)): + raise AssertionError() # Create array, do *not* copy data by default if copy: @@ -275,7 +277,8 @@ def take(self, indices, axis=0): ------- taken : ndarray """ - assert(axis == 0) + if not ((axis == 0)): + raise AssertionError() indices = np.asarray(indices, dtype=int) n = len(self) diff --git a/pandas/sparse/frame.py b/pandas/sparse/frame.py index 82719817b5744..ed33be33ac02a 100644 --- a/pandas/sparse/frame.py +++ b/pandas/sparse/frame.py @@ -709,7 +709,9 @@ def _join_compat(self, other, on=None, how='left', lsuffix='', rsuffix='', def _join_index(self, other, how, lsuffix, rsuffix): if isinstance(other, Series): - assert(other.name is not None) + if not (other.name is not None): + raise AssertionError() + other = SparseDataFrame({other.name: other}, default_fill_value=self.default_fill_value) diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py index bd5a2785aba2b..0b2842155b299 100644 --- a/pandas/sparse/panel.py +++ b/pandas/sparse/panel.py @@ -71,7 +71,8 @@ def __init__(self, frames, items=None, major_axis=None, minor_axis=None, default_kind=default_kind) frames = new_frames - assert(isinstance(frames, dict)) + if not (isinstance(frames, dict)): + raise AssertionError() self.default_fill_value = fill_value = default_fill_value self.default_kind = kind = default_kind diff --git a/pandas/sparse/series.py b/pandas/sparse/series.py index 8374c4ab9c373..bd01845a295b6 100644 --- a/pandas/sparse/series.py +++ b/pandas/sparse/series.py @@ -110,7 +110,8 @@ def __new__(cls, data, index=None, sparse_index=None, kind='block', if isinstance(data, SparseSeries) and index is None: index = data.index elif index is not None: - assert(len(index) == len(data)) + if not (len(index) == len(data)): + raise AssertionError() sparse_index = data.sp_index values = np.asarray(data) @@ -128,7 +129,8 @@ def __new__(cls, data, index=None, sparse_index=None, kind='block', fill_value=fill_value) else: values = data - assert(len(values) == sparse_index.npoints) + if not (len(values) == sparse_index.npoints): + raise AssertionError() else: if index is None: raise Exception('must pass index!') @@ -446,7 +448,8 @@ def sparse_reindex(self, new_index): ------- reindexed : SparseSeries """ - assert(isinstance(new_index, splib.SparseIndex)) + if not (isinstance(new_index, splib.SparseIndex)): + raise AssertionError() new_values = self.sp_index.to_int_index().reindex(self.sp_values, self.fill_value, diff --git a/pandas/stats/ols.py b/pandas/stats/ols.py index 9ecf5c6ab715f..e5324926ea1f0 100644 --- a/pandas/stats/ols.py +++ b/pandas/stats/ols.py @@ -619,7 +619,8 @@ def _set_window(self, window_type, window, min_periods): self._window_type = scom._get_window_type(window_type) if self._is_rolling: - assert(window is not None) + if not ((window is not None)): + raise AssertionError() if min_periods is None: min_periods = window else: @@ -1196,7 +1197,8 @@ def _nobs_raw(self): return result.astype(int) def _beta_matrix(self, lag=0): - assert(lag >= 0) + if not ((lag >= 0)): + raise AssertionError() betas = self._beta_raw @@ -1257,7 +1259,8 @@ def _filter_data(lhs, rhs, weights=None): Cleaned lhs and rhs """ if not isinstance(lhs, Series): - assert(len(lhs) == len(rhs)) + if not ((len(lhs) == len(rhs))): + raise AssertionError() lhs = Series(lhs, index=rhs.index) rhs = _combine_rhs(rhs) diff --git a/pandas/stats/plm.py b/pandas/stats/plm.py index 3173e05ae8e9d..467ce6a05e1f0 100644 --- a/pandas/stats/plm.py +++ b/pandas/stats/plm.py @@ -101,8 +101,10 @@ def _prepare_data(self): y_regressor = y if weights is not None: - assert(y_regressor.index.equals(weights.index)) - assert(x_regressor.index.equals(weights.index)) + if not ((y_regressor.index.equals(weights.index))): + raise AssertionError() + if not ((x_regressor.index.equals(weights.index))): + raise AssertionError() rt_weights = np.sqrt(weights) y_regressor = y_regressor * rt_weights @@ -169,7 +171,8 @@ def _convert_x(self, x): # .iteritems iteritems = getattr(x, 'iteritems', x.items) for key, df in iteritems(): - assert(isinstance(df, DataFrame)) + if not ((isinstance(df, DataFrame))): + raise AssertionError() if _is_numeric(df): x_converted[key] = df @@ -637,7 +640,8 @@ def _y_predict_raw(self): return (betas * x).sum(1) def _beta_matrix(self, lag=0): - assert(lag >= 0) + if not ((lag >= 0)): + raise AssertionError() index = self._y_trans.index major_labels = index.labels[0] diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py index 1643a6bfb2655..6d224ffcb7b05 100644 --- a/pandas/tools/merge.py +++ b/pandas/tools/merge.py @@ -404,14 +404,17 @@ def _validate_specification(self): elif self.left_on is not None: n = len(self.left_on) if self.right_index: - assert(len(self.left_on) == self.right.index.nlevels) + if not ((len(self.left_on) == self.right.index.nlevels)): + raise AssertionError() self.right_on = [None] * n elif self.right_on is not None: n = len(self.right_on) if self.left_index: - assert(len(self.right_on) == self.left.index.nlevels) + if not ((len(self.right_on) == self.left.index.nlevels)): + raise AssertionError() self.left_on = [None] * n - assert(len(self.right_on) == len(self.left_on)) + if not ((len(self.right_on) == len(self.left_on))): + raise AssertionError() 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'): ------- """ - assert(len(left_keys) == len(right_keys)) + if not ((len(left_keys) == len(right_keys))): + raise AssertionError() left_labels = [] right_labels = [] @@ -537,8 +541,9 @@ def _left_join_on_index(left_ax, right_ax, join_keys, sort=False): left_indexer = None if len(join_keys) > 1: - assert(isinstance(right_ax, MultiIndex) and - len(join_keys) == right_ax.nlevels) + if not ((isinstance(right_ax, MultiIndex) and + len(join_keys) == right_ax.nlevels) ): + raise AssertionError() left_tmp, right_indexer = \ _get_multiindex_indexer(join_keys, right_ax, @@ -637,7 +642,8 @@ def __init__(self, data_list, join_index, indexers, axis=1, copy=True): if axis <= 0: # pragma: no cover raise MergeError('Only axis >= 1 supported for this operation') - assert(len(data_list) == len(indexers)) + if not ((len(data_list) == len(indexers))): + raise AssertionError() self.units = [] for data, indexer in zip(data_list, indexers): @@ -925,7 +931,8 @@ def __init__(self, objs, axis=0, join='outer', join_axes=None, axis = 1 if axis == 0 else 0 self._is_series = isinstance(sample, Series) - assert(0 <= axis <= sample.ndim) + if not ((0 <= axis <= sample.ndim)): + raise AssertionError() # note: this is the BlockManager axis (since DataFrame is transposed) self.axis = axis @@ -1084,7 +1091,8 @@ def _concat_single_item(self, objs, item): to_concat.append(item_values) # this method only gets called with axis >= 1 - assert(self.axis >= 1) + if not ((self.axis >= 1)): + raise AssertionError() return com._concat_compat(to_concat, axis=self.axis - 1) def _get_result_dim(self): @@ -1103,7 +1111,8 @@ def _get_new_axes(self): continue new_axes[i] = self._get_comb_axis(i) else: - assert(len(self.join_axes) == ndim - 1) + if not ((len(self.join_axes) == ndim - 1)): + raise AssertionError() # ufff... indices = range(ndim) diff --git a/pandas/tools/pivot.py b/pandas/tools/pivot.py index ef605abb8e4fb..8d5ba7af0d92b 100644 --- a/pandas/tools/pivot.py +++ b/pandas/tools/pivot.py @@ -300,7 +300,8 @@ def _get_names(arrs, names, prefix='row'): else: names.append('%s_%d' % (prefix, i)) else: - assert(len(names) == len(arrs)) + if not ((len(names) == len(arrs))): + raise AssertionError() if not isinstance(names, list): names = list(names) diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py index dbc71760d50c7..0d29da83dbd8a 100644 --- a/pandas/tseries/index.py +++ b/pandas/tseries/index.py @@ -308,7 +308,9 @@ def _generate(cls, start, end, periods, name, offset, tz = tools._maybe_get_tz(tz) if tz is not None and inferred_tz is not None: - assert(inferred_tz == tz) + if not inferred_tz == tz: + raise AssertionError() + elif inferred_tz is not None: tz = inferred_tz @@ -451,14 +453,17 @@ def _cached_range(cls, start=None, end=None, periods=None, offset=None, cachedRange = drc[offset] if start is None: - assert(isinstance(end, Timestamp)) + if not (isinstance(end, Timestamp)): + raise AssertionError() end = offset.rollback(end) endLoc = cachedRange.get_loc(end) + 1 startLoc = endLoc - periods elif end is None: - assert(isinstance(start, Timestamp)) + if not (isinstance(start, Timestamp)): + raise AssertionError() + start = offset.rollforward(start) startLoc = cachedRange.get_loc(start) diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py index a405fda1c4fe4..c1af7ba5cccc2 100644 --- a/pandas/tseries/period.py +++ b/pandas/tseries/period.py @@ -500,10 +500,13 @@ def _period_index_cmp(opname): def wrapper(self, other): if isinstance(other, Period): func = getattr(self.values, opname) - assert(other.freq == self.freq) + if not (other.freq == self.freq): + raise AssertionError() + result = func(other.ordinal) elif isinstance(other, PeriodIndex): - assert(other.freq == self.freq) + if not (other.freq == self.freq): + raise AssertionError() return getattr(self.values, opname)(other.values) else: other = Period(other, freq=self.freq) @@ -1230,7 +1233,8 @@ def _range_from_fields(year=None, month=None, quarter=None, day=None, base, mult = _gfc(freq) if mult != 1: raise ValueError('Only mult == 1 supported') - assert(base == FreqGroup.FR_QTR) + if not (base == FreqGroup.FR_QTR): + raise AssertionError() year, quarter = _make_field_arrays(year, quarter) for y, q in zip(year, quarter): diff --git a/pandas/tseries/resample.py b/pandas/tseries/resample.py index 57f861aff8bfc..4bf0a5bf3182c 100644 --- a/pandas/tseries/resample.py +++ b/pandas/tseries/resample.py @@ -119,7 +119,8 @@ def _get_time_grouper(self, obj): return binner, grouper def _get_time_bins(self, axis): - assert(isinstance(axis, DatetimeIndex)) + if not (isinstance(axis, DatetimeIndex)): + raise AssertionError() if len(axis) == 0: binner = labels = DatetimeIndex(data=[], freq=self.freq) @@ -178,7 +179,8 @@ def _adjust_bin_edges(self, binner, ax_values): return binner, bin_edges def _get_time_period_bins(self, axis): - assert(isinstance(axis, DatetimeIndex)) + if not(isinstance(axis, DatetimeIndex)): + raise AssertionError() if len(axis) == 0: binner = labels = PeriodIndex(data=[], freq=self.freq) @@ -208,7 +210,8 @@ def _resample_timestamps(self, obj): result = grouped.aggregate(self._agg_method) else: # upsampling shortcut - assert(self.axis == 0) + if not (self.axis == 0): + raise AssertionError() if self.closed == 'right': res_index = binner[1:] diff --git a/pandas/tseries/tools.py b/pandas/tseries/tools.py index e35b80fff013f..f9608be013b3c 100644 --- a/pandas/tseries/tools.py +++ b/pandas/tseries/tools.py @@ -28,7 +28,8 @@ def _infer_tzinfo(start, end): def _infer(a, b): tz = a.tzinfo if b and b.tzinfo: - assert(tslib.get_timezone(tz) == tslib.get_timezone(b.tzinfo)) + if not (tslib.get_timezone(tz) == tslib.get_timezone(b.tzinfo)): + raise AssertionError() return tz tz = None if start is not None: diff --git a/pandas/util/decorators.py b/pandas/util/decorators.py index 15ab39d07ec4d..97b2ee3353fa3 100644 --- a/pandas/util/decorators.py +++ b/pandas/util/decorators.py @@ -46,8 +46,9 @@ def some_function(x): "%s %s wrote the Raven" """ def __init__(self, *args, **kwargs): - assert not ( - args and kwargs), "Only positional or keyword args are allowed" + if (args and kwargs): + raise AssertionError( "Only positional or keyword args are allowed") + self.params = args or kwargs def __call__(self, func):