Skip to content

Commit c44bad2

Browse files
pambotjreback
authored andcommitted
CLN GH22873 Replace base excepts in pandas/core (pandas-dev#22901)
1 parent 8e749a3 commit c44bad2

File tree

14 files changed

+36
-33
lines changed

14 files changed

+36
-33
lines changed

doc/source/whatsnew/v0.24.0.txt

-1
Original file line numberDiff line numberDiff line change
@@ -834,4 +834,3 @@ Other
834834
- :meth:`DataFrame.nlargest` and :meth:`DataFrame.nsmallest` now returns the correct n values when keep != 'all' also when tied on the first columns (:issue:`22752`)
835835
- :meth:`~pandas.io.formats.style.Styler.bar` now also supports tablewise application (in addition to rowwise and columnwise) with ``axis=None`` and setting clipping range with ``vmin`` and ``vmax`` (:issue:`21548` and :issue:`21526`). ``NaN`` values are also handled properly.
836836
- Logical operations ``&, |, ^`` between :class:`Series` and :class:`Index` will no longer raise ``ValueError`` (:issue:`22092`)
837-
-

pandas/core/computation/pytables.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@ def visit_Subscript(self, node, **kwargs):
411411
slobj = self.visit(node.slice)
412412
try:
413413
value = value.value
414-
except:
414+
except AttributeError:
415415
pass
416416

417417
try:

pandas/core/dtypes/common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ def is_timedelta64_dtype(arr_or_dtype):
467467
return False
468468
try:
469469
tipo = _get_dtype_type(arr_or_dtype)
470-
except:
470+
except (TypeError, ValueError, SyntaxError):
471471
return False
472472
return issubclass(tipo, np.timedelta64)
473473

pandas/core/dtypes/dtypes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -358,11 +358,11 @@ def construct_from_string(cls, string):
358358
try:
359359
if string == 'category':
360360
return cls()
361-
except:
361+
else:
362+
raise TypeError("cannot construct a CategoricalDtype")
363+
except AttributeError:
362364
pass
363365

364-
raise TypeError("cannot construct a CategoricalDtype")
365-
366366
@staticmethod
367367
def validate_ordered(ordered):
368368
"""
@@ -519,7 +519,7 @@ def __new__(cls, unit=None, tz=None):
519519
if m is not None:
520520
unit = m.groupdict()['unit']
521521
tz = m.groupdict()['tz']
522-
except:
522+
except TypeError:
523523
raise ValueError("could not construct DatetimeTZDtype")
524524

525525
elif isinstance(unit, compat.string_types):

pandas/core/frame.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3260,7 +3260,7 @@ def _ensure_valid_index(self, value):
32603260
if not len(self.index) and is_list_like(value):
32613261
try:
32623262
value = Series(value)
3263-
except:
3263+
except (ValueError, NotImplementedError, TypeError):
32643264
raise ValueError('Cannot set a frame with no defined index '
32653265
'and a value that cannot be converted to a '
32663266
'Series')
@@ -7750,7 +7750,7 @@ def convert(v):
77507750
values = np.array([convert(v) for v in values])
77517751
else:
77527752
values = convert(values)
7753-
except:
7753+
except (ValueError, TypeError):
77547754
values = convert(values)
77557755

77567756
else:

pandas/core/indexes/frozen.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def searchsorted(self, value, side="left", sorter=None):
139139
# xref: https://github.com/numpy/numpy/issues/5370
140140
try:
141141
value = self.dtype.type(value)
142-
except:
142+
except ValueError:
143143
pass
144144

145145
return super(FrozenNDArray, self).searchsorted(

pandas/core/indexes/multi.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import numpy as np
88
from pandas._libs import algos as libalgos, index as libindex, lib, Timestamp
9+
from pandas._libs import tslibs
910

1011
from pandas.compat import range, zip, lrange, lzip, map
1112
from pandas.compat.numpy import function as nv
@@ -1002,12 +1003,13 @@ def _try_mi(k):
10021003
return _try_mi(key)
10031004
except (KeyError):
10041005
raise
1005-
except:
1006+
except (IndexError, ValueError, TypeError):
10061007
pass
10071008

10081009
try:
10091010
return _try_mi(Timestamp(key))
1010-
except:
1011+
except (KeyError, TypeError,
1012+
IndexError, ValueError, tslibs.OutOfBoundsDatetime):
10111013
pass
10121014

10131015
raise InvalidIndexError(key)
@@ -1686,7 +1688,7 @@ def append(self, other):
16861688
# if all(isinstance(x, MultiIndex) for x in other):
16871689
try:
16881690
return MultiIndex.from_tuples(new_tuples, names=self.names)
1689-
except:
1691+
except (TypeError, IndexError):
16901692
return Index(new_tuples)
16911693

16921694
def argsort(self, *args, **kwargs):
@@ -2315,7 +2317,7 @@ def maybe_droplevels(indexer, levels, drop_level):
23152317
for i in sorted(levels, reverse=True):
23162318
try:
23172319
new_index = new_index.droplevel(i)
2318-
except:
2320+
except ValueError:
23192321

23202322
# no dropping here
23212323
return orig_index
@@ -2818,7 +2820,7 @@ def _convert_can_do_setop(self, other):
28182820
msg = 'other must be a MultiIndex or a list of tuples'
28192821
try:
28202822
other = MultiIndex.from_tuples(other)
2821-
except:
2823+
except TypeError:
28222824
raise TypeError(msg)
28232825
else:
28242826
result_names = self.names if self.names == other.names else None

pandas/core/indexing.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2146,7 +2146,7 @@ def _getitem_tuple(self, tup):
21462146
self._has_valid_tuple(tup)
21472147
try:
21482148
return self._getitem_lowerdim(tup)
2149-
except:
2149+
except IndexingError:
21502150
pass
21512151

21522152
retval = self.obj
@@ -2705,13 +2705,13 @@ def maybe_droplevels(index, key):
27052705
for _ in key:
27062706
try:
27072707
index = index.droplevel(0)
2708-
except:
2708+
except ValueError:
27092709
# we have dropped too much, so back out
27102710
return original_index
27112711
else:
27122712
try:
27132713
index = index.droplevel(0)
2714-
except:
2714+
except ValueError:
27152715
pass
27162716

27172717
return index

pandas/core/internals/blocks.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None,
666666

667667
newb = make_block(values, placement=self.mgr_locs,
668668
klass=klass, ndim=self.ndim)
669-
except:
669+
except Exception: # noqa: E722
670670
if errors == 'raise':
671671
raise
672672
newb = self.copy() if copy else self
@@ -1142,7 +1142,7 @@ def check_int_bool(self, inplace):
11421142
# a fill na type method
11431143
try:
11441144
m = missing.clean_fill_method(method)
1145-
except:
1145+
except ValueError:
11461146
m = None
11471147

11481148
if m is not None:
@@ -1157,7 +1157,7 @@ def check_int_bool(self, inplace):
11571157
# try an interp method
11581158
try:
11591159
m = missing.clean_interp_method(method, **kwargs)
1160-
except:
1160+
except ValueError:
11611161
m = None
11621162

11631163
if m is not None:
@@ -2438,7 +2438,7 @@ def set(self, locs, values, check=False):
24382438
try:
24392439
if (self.values[locs] == values).all():
24402440
return
2441-
except:
2441+
except (IndexError, ValueError):
24422442
pass
24432443
try:
24442444
self.values[locs] = values
@@ -3172,7 +3172,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None,
31723172
def __len__(self):
31733173
try:
31743174
return self.sp_index.length
3175-
except:
3175+
except AttributeError:
31763176
return 0
31773177

31783178
def copy(self, deep=True, mgr=None):

pandas/core/nanops.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,8 @@ def reduction(values, axis=None, skipna=True):
503503
try:
504504
result = getattr(values, meth)(axis, dtype=dtype_max)
505505
result.fill(np.nan)
506-
except:
506+
except (AttributeError, TypeError,
507+
ValueError, np.core._internal.AxisError):
507508
result = np.nan
508509
else:
509510
result = getattr(values, meth)(axis)
@@ -815,7 +816,7 @@ def _ensure_numeric(x):
815816
elif is_object_dtype(x):
816817
try:
817818
x = x.astype(np.complex128)
818-
except:
819+
except (TypeError, ValueError):
819820
x = x.astype(np.float64)
820821
else:
821822
if not np.any(x.imag):

pandas/core/ops.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1545,7 +1545,8 @@ def na_op(x, y):
15451545
y = bool(y)
15461546
try:
15471547
result = libops.scalar_binop(x, y, op)
1548-
except:
1548+
except (TypeError, ValueError, AttributeError,
1549+
OverflowError, NotImplementedError):
15491550
raise TypeError("cannot compare a dtyped [{dtype}] array "
15501551
"with a scalar of type [{typ}]"
15511552
.format(dtype=x.dtype,

pandas/core/sparse/array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ def __setstate__(self, state):
306306
def __len__(self):
307307
try:
308308
return self.sp_index.length
309-
except:
309+
except AttributeError:
310310
return 0
311311

312312
def __unicode__(self):

pandas/core/tools/datetimes.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None,
244244
if format == '%Y%m%d':
245245
try:
246246
result = _attempt_YYYYMMDD(arg, errors=errors)
247-
except:
247+
except (ValueError, TypeError, tslibs.OutOfBoundsDatetime):
248248
raise ValueError("cannot convert the input to "
249249
"'%Y%m%d' date format")
250250

@@ -334,7 +334,7 @@ def _adjust_to_origin(arg, origin, unit):
334334
raise ValueError("unit must be 'D' for origin='julian'")
335335
try:
336336
arg = arg - j0
337-
except:
337+
except TypeError:
338338
raise ValueError("incompatible 'arg' type for given "
339339
"'origin'='julian'")
340340

@@ -731,21 +731,21 @@ def calc_with_mask(carg, mask):
731731
# try intlike / strings that are ints
732732
try:
733733
return calc(arg.astype(np.int64))
734-
except:
734+
except ValueError:
735735
pass
736736

737737
# a float with actual np.nan
738738
try:
739739
carg = arg.astype(np.float64)
740740
return calc_with_mask(carg, notna(carg))
741-
except:
741+
except ValueError:
742742
pass
743743

744744
# string with NaN-like
745745
try:
746746
mask = ~algorithms.isin(arg, list(tslib.nat_strings))
747747
return calc_with_mask(arg, mask)
748-
except:
748+
except ValueError:
749749
pass
750750

751751
return None

pandas/core/window.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2504,7 +2504,7 @@ def _offset(window, center):
25042504
offset = (window - 1) / 2. if center else 0
25052505
try:
25062506
return int(offset)
2507-
except:
2507+
except TypeError:
25082508
return offset.astype(int)
25092509

25102510

0 commit comments

Comments
 (0)