Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the prototypical definition of sequence __getitem__ in Python?

Right now, I'm doing this:

class EdgesGenerator(abc.Sequence):

    def __init__(self, link, size):
        self.link = link
        self.size = size

    def __getitem__(self, cluster_index):
        try:
            index = cluster_index.__index__()
        except AttributeError:
            raise TypeError from None
        if 0 <= index < self.size:
            return Edge(self.link, index)
        raise IndexError

    def __len__(self):
        return self.size

Is this the prototypical __getitem__ for a sequence? How should it be written?

like image 990
Neil G Avatar asked Oct 11 '26 03:10

Neil G


1 Answers

As correctly given in the comments by @Cristian, the only standard pattern I know of is from documentation -

object.__getitem__(self, key)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

But there is another issue I see with your implementation , For each valid call to __getitem__() , that is for something like object[index] . You are creating a new Edge object everytime.

So everytime you call object[index] , you would receive a new Edge object (though the contents of that edge object may be identical) , but the object itself would be new.

So things like - object[index] is object[index] would most probably fail (would result False) .

Unless this is something you intended , you should try caching the Edge objects (and returning from cache if found) . I would suggest using a dictionary to cache the objects (since you seem to be creating objects on the fly , only when accessed) , though you can also use a list, you would just need to initialize the list to have size as self.size .

like image 94
Anand S Kumar Avatar answered Oct 12 '26 15:10

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!