Skip to content

Commit 6ce48d9

Browse files
jbrockmendelBlake Hawkins
authored and
Blake Hawkins
committed
CLN: tighten exception catching in indexes (pandas-dev#29078)
1 parent 1939942 commit 6ce48d9

File tree

3 files changed

+14
-16
lines changed

3 files changed

+14
-16
lines changed

pandas/core/indexes/base.py

+4-13
Original file line numberDiff line numberDiff line change
@@ -3142,16 +3142,7 @@ def is_int(v):
31423142
elif is_positional:
31433143
indexer = key
31443144
else:
3145-
try:
3146-
indexer = self.slice_indexer(start, stop, step, kind=kind)
3147-
except Exception:
3148-
if is_index_slice:
3149-
if self.is_integer():
3150-
raise
3151-
else:
3152-
indexer = key
3153-
else:
3154-
raise
3145+
indexer = self.slice_indexer(start, stop, step, kind=kind)
31553146

31563147
return indexer
31573148

@@ -4676,11 +4667,11 @@ def get_value(self, series, key):
46764667
raise InvalidIndexError(key)
46774668
else:
46784669
raise e1
4679-
except Exception: # pragma: no cover
4670+
except Exception:
46804671
raise e1
46814672
except TypeError:
4682-
# python 3
4683-
if is_scalar(key): # pragma: no cover
4673+
# e.g. "[False] is an invalid key"
4674+
if is_scalar(key):
46844675
raise IndexError(key)
46854676
raise InvalidIndexError(key)
46864677

pandas/core/indexes/period.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,11 @@ def __contains__(self, key):
457457
try:
458458
self.get_loc(key)
459459
return True
460-
except Exception:
460+
except (ValueError, TypeError, KeyError):
461+
# TypeError can be reached if we pass a tuple that is not hashable
462+
# ValueError can be reached if pass a 2-tuple and parse_time_string
463+
# raises with the wrong number of return values
464+
# TODO: the latter is a bug in parse_time_string
461465
return False
462466

463467
@cache_readonly
@@ -765,7 +769,9 @@ def _maybe_cast_slice_bound(self, label, side, kind):
765769
_, parsed, reso = parse_time_string(label, self.freq)
766770
bounds = self._parsed_string_to_bounds(reso, parsed)
767771
return bounds[0 if side == "left" else 1]
768-
except Exception:
772+
except ValueError:
773+
# string cannot be parsed as datetime-like
774+
# TODO: we need tests for this case
769775
raise KeyError(label)
770776
elif is_integer(label) or is_float(label):
771777
self._invalid_indexer("slice", label)

pandas/core/indexes/timedeltas.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -630,7 +630,8 @@ def insert(self, loc, item):
630630
if _is_convertible_to_td(item):
631631
try:
632632
item = Timedelta(item)
633-
except Exception:
633+
except ValueError:
634+
# e.g. str that can't be parsed to timedelta
634635
pass
635636
elif is_scalar(item) and isna(item):
636637
# GH 18295

0 commit comments

Comments
 (0)