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
2
3
import warnings
3
4
4
5
import numpy as np
@@ -610,17 +611,13 @@ def _get_setitem_indexer(self, key):
610
611
ax = self .obj ._get_axis (0 )
611
612
612
613
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 ):
616
615
# TypeError e.g. passed a bool
617
- pass
616
+ return ax . get_loc ( key )
618
617
619
618
if isinstance (key , tuple ):
620
- try :
619
+ with suppress ( IndexingError ) :
621
620
return self ._convert_tuple (key , is_setter = True )
622
- except IndexingError :
623
- pass
624
621
625
622
if isinstance (key , range ):
626
623
return list (key )
@@ -707,9 +704,8 @@ def _has_valid_tuple(self, key: Tuple):
707
704
"""
708
705
Check the key for valid keys across my indexer.
709
706
"""
707
+ self ._validate_key_length (key )
710
708
for i , k in enumerate (key ):
711
- if i >= self .ndim :
712
- raise IndexingError ("Too many indexers" )
713
709
try :
714
710
self ._validate_key (k , i )
715
711
except ValueError as err :
@@ -740,13 +736,17 @@ def _convert_tuple(self, key, is_setter: bool = False):
740
736
else :
741
737
keyidx .append (slice (None ))
742
738
else :
739
+ self ._validate_key_length (key )
743
740
for i , k in enumerate (key ):
744
- if i >= self .ndim :
745
- raise IndexingError ("Too many indexers" )
746
741
idx = self ._convert_to_indexer (k , axis = i , is_setter = is_setter )
747
742
keyidx .append (idx )
743
+
748
744
return tuple (keyidx )
749
745
746
+ def _validate_key_length (self , key : Sequence [Any ]) -> None :
747
+ if len (key ) > self .ndim :
748
+ raise IndexingError ("Too many indexers" )
749
+
750
750
def _getitem_tuple_same_dim (self , tup : Tuple ):
751
751
"""
752
752
Index with indexers that should return an object of the same dimension
@@ -782,14 +782,10 @@ def _getitem_lowerdim(self, tup: Tuple):
782
782
# ...but iloc should handle the tuple as simple integer-location
783
783
# instead of checking it as multiindex representation (GH 13797)
784
784
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 )
790
787
791
- if len (tup ) > self .ndim :
792
- raise IndexingError ("Too many indexers. handle elsewhere" )
788
+ self ._validate_key_length (tup )
793
789
794
790
for i , key in enumerate (tup ):
795
791
if is_label_like (key ):
@@ -834,11 +830,8 @@ def _getitem_nested_tuple(self, tup: Tuple):
834
830
if self .name != "loc" :
835
831
# This should never be reached, but lets be explicit about it
836
832
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 )
842
835
843
836
# this is a series with a multi-index specified a tuple of
844
837
# selectors
@@ -877,11 +870,9 @@ def __getitem__(self, key):
877
870
if type (key ) is tuple :
878
871
key = tuple (com .apply_if_callable (x , self .obj ) for x in key )
879
872
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 ):
883
874
# AttributeError for IntervalTree get_value
884
- pass
875
+ return self . obj . _get_value ( * key , takeable = self . _takeable )
885
876
return self ._getitem_tuple (key )
886
877
else :
887
878
# we by definition only have the 0th axis
@@ -1052,10 +1043,8 @@ def _getitem_iterable(self, key, axis: int):
1052
1043
)
1053
1044
1054
1045
def _getitem_tuple (self , tup : Tuple ):
1055
- try :
1046
+ with suppress ( IndexingError ) :
1056
1047
return self ._getitem_lowerdim (tup )
1057
- except IndexingError :
1058
- pass
1059
1048
1060
1049
# no multi-index, so validate all of the indexers
1061
1050
self ._has_valid_tuple (tup )
@@ -1082,7 +1071,7 @@ def _handle_lowerdim_multi_index_axis0(self, tup: Tuple):
1082
1071
except KeyError as ek :
1083
1072
# raise KeyError if number of indexers match
1084
1073
# 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 :
1086
1075
raise ek
1087
1076
1088
1077
raise IndexingError ("No label returned" )
@@ -1295,8 +1284,6 @@ def _validate_read_indexer(
1295
1284
If at least one key was requested but none was found, and
1296
1285
raise_missing=True.
1297
1286
"""
1298
- ax = self .obj ._get_axis (axis )
1299
-
1300
1287
if len (key ) == 0 :
1301
1288
return
1302
1289
@@ -1309,6 +1296,8 @@ def _validate_read_indexer(
1309
1296
axis_name = self .obj ._get_axis_name (axis )
1310
1297
raise KeyError (f"None of [{ key } ] are in the [{ axis_name } ]" )
1311
1298
1299
+ ax = self .obj ._get_axis (axis )
1300
+
1312
1301
# We (temporarily) allow for some missing keys with .loc, except in
1313
1302
# some cases (e.g. setting) in which "raise_missing" will be False
1314
1303
if raise_missing :
@@ -1391,21 +1380,22 @@ def _has_valid_setitem_indexer(self, indexer) -> bool:
1391
1380
"""
1392
1381
if isinstance (indexer , dict ):
1393
1382
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 ):
1408
1396
raise IndexError ("iloc cannot enlarge its target object" )
1397
+ elif isinstance (i , dict ):
1398
+ raise IndexError ("iloc cannot enlarge its target object" )
1409
1399
1410
1400
return True
1411
1401
@@ -1453,10 +1443,8 @@ def _validate_integer(self, key: int, axis: int) -> None:
1453
1443
def _getitem_tuple (self , tup : Tuple ):
1454
1444
1455
1445
self ._has_valid_tuple (tup )
1456
- try :
1446
+ with suppress ( IndexingError ) :
1457
1447
return self ._getitem_lowerdim (tup )
1458
- except IndexingError :
1459
- pass
1460
1448
1461
1449
return self ._getitem_tuple_same_dim (tup )
1462
1450
@@ -2286,15 +2274,10 @@ def maybe_convert_ix(*args):
2286
2274
"""
2287
2275
We likely want to take the cross-product.
2288
2276
"""
2289
- ixify = True
2290
2277
for arg in args :
2291
2278
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 )
2298
2281
2299
2282
2300
2283
def is_nested_tuple (tup , labels ) -> bool :
0 commit comments