__Getitem__ implementation

Is there a way to implement __getitem__in a way that supports integer and slice indices without manually checking the type of the argument?

I see many examples of this form, but it seems very hoarse to me.

def __getitem__(self,key):
  if isinstance(key,int):
    # do integery foo here
  if isinstance(key,slice):
    # do slicey bar here

On the other hand, why does this problem exist in the first place? Sometimes an int is returned, and sometimes a fragment is a strange design. The call foo[4]should call foo.__getitem__(slice(4,5,1))or similar.

+4
source share
1 answer

You can use exception handling; Suppose that it keyis an object sliceand calls a method indices(). If this fails, it must be an integer:

def __getitem__(self, key):
    try:
        return [self.somelist[i] * 5 for i in key.indices(self.length)]
    except AttributeError:
        # not a slice object (no `indices` attribute)
        return self.somelist[key] * 5

, __getitem__ ( , ); __getslice__() , . __getslice__ , API __getitem__ , slice.

, key . , .

+5

Source: https://habr.com/ru/post/1529834/


All Articles