Skip to content

Commit 09e7829

Browse files
authored
CLN: pandas/core/indexing.py (#36713)
1 parent 50c4fbc commit 09e7829

File tree

1 file changed

+41
-58
lines changed

1 file changed

+41
-58
lines changed

pandas/core/indexing.py

+41-58
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from typing import TYPE_CHECKING, Hashable, List, Tuple, Union
1+
from contextlib import suppress
2+
from typing import TYPE_CHECKING, Any, Hashable, List, Sequence, Tuple, Union
23
import warnings
34

45
import numpy as np
@@ -610,17 +611,13 @@ def _get_setitem_indexer(self, key):
610611
ax = self.obj._get_axis(0)
611612

612613
if isinstance(ax, ABCMultiIndex) and self.name != "iloc":
613-
try:
614-
return ax.get_loc(key)
615-
except (TypeError, KeyError, InvalidIndexError):
614+
with suppress(TypeError, KeyError, InvalidIndexError):
616615
# TypeError e.g. passed a bool
617-
pass
616+
return ax.get_loc(key)
618617

619618
if isinstance(key, tuple):
620-
try:
619+
with suppress(IndexingError):
621620
return self._convert_tuple(key, is_setter=True)
622-
except IndexingError:
623-
pass
624621

625622
if isinstance(key, range):
626623
return list(key)
@@ -707,9 +704,8 @@ def _has_valid_tuple(self, key: Tuple):
707704
"""
708705
Check the key for valid keys across my indexer.
709706
"""
707+
self._validate_key_length(key)
710708
for i, k in enumerate(key):
711-
if i >= self.ndim:
712-
raise IndexingError("Too many indexers")
713709
try:
714710
self._validate_key(k, i)
715711
except ValueError as err:
@@ -740,13 +736,17 @@ def _convert_tuple(self, key, is_setter: bool = False):
740736
else:
741737
keyidx.append(slice(None))
742738
else:
739+
self._validate_key_length(key)
743740
for i, k in enumerate(key):
744-
if i >= self.ndim:
745-
raise IndexingError("Too many indexers")
746741
idx = self._convert_to_indexer(k, axis=i, is_setter=is_setter)
747742
keyidx.append(idx)
743+
748744
return tuple(keyidx)
749745

746+
def _validate_key_length(self, key: Sequence[Any]) -> None:
747+
if len(key) > self.ndim:
748+
raise IndexingError("Too many indexers")
749+
750750
def _getitem_tuple_same_dim(self, tup: Tuple):
751751
"""
752752
Index with indexers that should return an object of the same dimension
@@ -782,14 +782,10 @@ def _getitem_lowerdim(self, tup: Tuple):
782782
# ...but iloc should handle the tuple as simple integer-location
783783
# instead of checking it as multiindex representation (GH 13797)
784784
if isinstance(ax0, ABCMultiIndex) and self.name != "iloc":
785-
try:
786-
result = self._handle_lowerdim_multi_index_axis0(tup)
787-
return result
788-
except IndexingError:
789-
pass
785+
with suppress(IndexingError):
786+
return self._handle_lowerdim_multi_index_axis0(tup)
790787

791-
if len(tup) > self.ndim:
792-
raise IndexingError("Too many indexers. handle elsewhere")
788+
self._validate_key_length(tup)
793789

794790
for i, key in enumerate(tup):
795791
if is_label_like(key):
@@ -834,11 +830,8 @@ def _getitem_nested_tuple(self, tup: Tuple):
834830
if self.name != "loc":
835831
# This should never be reached, but lets be explicit about it
836832
raise ValueError("Too many indices")
837-
try:
838-
result = self._handle_lowerdim_multi_index_axis0(tup)
839-
return result
840-
except IndexingError:
841-
pass
833+
with suppress(IndexingError):
834+
return self._handle_lowerdim_multi_index_axis0(tup)
842835

843836
# this is a series with a multi-index specified a tuple of
844837
# selectors
@@ -877,11 +870,9 @@ def __getitem__(self, key):
877870
if type(key) is tuple:
878871
key = tuple(com.apply_if_callable(x, self.obj) for x in key)
879872
if self._is_scalar_access(key):
880-
try:
881-
return self.obj._get_value(*key, takeable=self._takeable)
882-
except (KeyError, IndexError, AttributeError):
873+
with suppress(KeyError, IndexError, AttributeError):
883874
# AttributeError for IntervalTree get_value
884-
pass
875+
return self.obj._get_value(*key, takeable=self._takeable)
885876
return self._getitem_tuple(key)
886877
else:
887878
# we by definition only have the 0th axis
@@ -1052,10 +1043,8 @@ def _getitem_iterable(self, key, axis: int):
10521043
)
10531044

10541045
def _getitem_tuple(self, tup: Tuple):
1055-
try:
1046+
with suppress(IndexingError):
10561047
return self._getitem_lowerdim(tup)
1057-
except IndexingError:
1058-
pass
10591048

10601049
# no multi-index, so validate all of the indexers
10611050
self._has_valid_tuple(tup)
@@ -1082,7 +1071,7 @@ def _handle_lowerdim_multi_index_axis0(self, tup: Tuple):
10821071
except KeyError as ek:
10831072
# raise KeyError if number of indexers match
10841073
# else IndexingError will be raised
1085-
if len(tup) <= self.obj.index.nlevels and len(tup) > self.ndim:
1074+
if self.ndim < len(tup) <= self.obj.index.nlevels:
10861075
raise ek
10871076

10881077
raise IndexingError("No label returned")
@@ -1295,8 +1284,6 @@ def _validate_read_indexer(
12951284
If at least one key was requested but none was found, and
12961285
raise_missing=True.
12971286
"""
1298-
ax = self.obj._get_axis(axis)
1299-
13001287
if len(key) == 0:
13011288
return
13021289

@@ -1309,6 +1296,8 @@ def _validate_read_indexer(
13091296
axis_name = self.obj._get_axis_name(axis)
13101297
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
13111298

1299+
ax = self.obj._get_axis(axis)
1300+
13121301
# We (temporarily) allow for some missing keys with .loc, except in
13131302
# some cases (e.g. setting) in which "raise_missing" will be False
13141303
if raise_missing:
@@ -1391,21 +1380,22 @@ def _has_valid_setitem_indexer(self, indexer) -> bool:
13911380
"""
13921381
if isinstance(indexer, dict):
13931382
raise IndexError("iloc cannot enlarge its target object")
1394-
else:
1395-
if not isinstance(indexer, tuple):
1396-
indexer = _tuplify(self.ndim, indexer)
1397-
for ax, i in zip(self.obj.axes, indexer):
1398-
if isinstance(i, slice):
1399-
# should check the stop slice?
1400-
pass
1401-
elif is_list_like_indexer(i):
1402-
# should check the elements?
1403-
pass
1404-
elif is_integer(i):
1405-
if i >= len(ax):
1406-
raise IndexError("iloc cannot enlarge its target object")
1407-
elif isinstance(i, dict):
1383+
1384+
if not isinstance(indexer, tuple):
1385+
indexer = _tuplify(self.ndim, indexer)
1386+
1387+
for ax, i in zip(self.obj.axes, indexer):
1388+
if isinstance(i, slice):
1389+
# should check the stop slice?
1390+
pass
1391+
elif is_list_like_indexer(i):
1392+
# should check the elements?
1393+
pass
1394+
elif is_integer(i):
1395+
if i >= len(ax):
14081396
raise IndexError("iloc cannot enlarge its target object")
1397+
elif isinstance(i, dict):
1398+
raise IndexError("iloc cannot enlarge its target object")
14091399

14101400
return True
14111401

@@ -1453,10 +1443,8 @@ def _validate_integer(self, key: int, axis: int) -> None:
14531443
def _getitem_tuple(self, tup: Tuple):
14541444

14551445
self._has_valid_tuple(tup)
1456-
try:
1446+
with suppress(IndexingError):
14571447
return self._getitem_lowerdim(tup)
1458-
except IndexingError:
1459-
pass
14601448

14611449
return self._getitem_tuple_same_dim(tup)
14621450

@@ -2286,15 +2274,10 @@ def maybe_convert_ix(*args):
22862274
"""
22872275
We likely want to take the cross-product.
22882276
"""
2289-
ixify = True
22902277
for arg in args:
22912278
if not isinstance(arg, (np.ndarray, list, ABCSeries, Index)):
2292-
ixify = False
2293-
2294-
if ixify:
2295-
return np.ix_(*args)
2296-
else:
2297-
return args
2279+
return args
2280+
return np.ix_(*args)
22982281

22992282

23002283
def is_nested_tuple(tup, labels) -> bool:

0 commit comments

Comments
 (0)