From 1c823ad98f4fa94fc78bb10246f2414a34a509aa Mon Sep 17 00:00:00 2001 From: Brock Date: Wed, 22 Sep 2021 12:20:18 -0700 Subject: [PATCH 1/2] REF: DatetimeEngine.__contains__ --- pandas/_libs/index.pyx | 19 ++++++------------- pandas/core/generic.py | 2 ++ 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 31b507e9b7800..82c0132ce1052 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -418,19 +418,12 @@ cdef class DatetimeEngine(Int64Engine): def __contains__(self, val: object) -> bool: # We assume before we get here: # - val is hashable - cdef: - int64_t loc, conv - - conv = self._unbox_scalar(val) - if self.over_size_threshold and self.is_monotonic_increasing: - if not self.is_unique: - return self._get_loc_duplicates(conv) - values = self.values - loc = values.searchsorted(conv, side='left') - return values[loc] == conv - - self._ensure_mapping_populated() - return conv in self.mapping + self._unbox_scalar(val) + try: + self.get_loc(val) + return True + except (KeyError, TypeError): + return False cdef _call_monotonic(self, values): return algos.is_monotonic(values, timelike=True) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ae5b580c8070d..4321610521f97 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3953,6 +3953,8 @@ def __delitem__(self, key) -> None: maybe_shortcut = False if self.ndim == 2 and isinstance(self.columns, MultiIndex): try: + # By using engine's __contains__ we effectively + # restrict to same-length tuples maybe_shortcut = key not in self.columns._engine except TypeError: pass From 8d90a0315af1e7f7d22bfe2fb021ba05cc0fdea2 Mon Sep 17 00:00:00 2001 From: Brock Date: Wed, 22 Sep 2021 12:55:29 -0700 Subject: [PATCH 2/2] dont catch TypeError --- pandas/_libs/index.pyx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 82c0132ce1052..d7de9a25cecda 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -422,7 +422,7 @@ cdef class DatetimeEngine(Int64Engine): try: self.get_loc(val) return True - except (KeyError, TypeError): + except KeyError: return False cdef _call_monotonic(self, values):