Custom list class __getitem__ method fails

I have my custom list class called Stack like so:

class Stack():
  def __init__(self):
    self.items = []

  def append(self, item):
  def __getitem__(self, slc):
    if isinstance(slc, int):
      return self.items[slc]
      return self.__class__(self.items[slc])

Notice the __getitem__ method which I use for slicing functionality. It casts a type on a sliced list. This is also the same what the collections.UserList or are doing.

Now I want to inherit Stack and populate stack.items with some data. some_data is a regular python list which contains [[1, 2, 3], [4, 5, 6],...], I do it like so:

class SpecificStack(Stack):
  def __init__(self, some_data):
    for d in some_data:
       item = {'time': d[0], 'place': d[1], 'order': d[2]}
       self.append( item )

If I now try to slice SpecificStack object instance:

ss = SpecificStack(some_data)

The __getitem__ slicing functionality goes wrong. I get KeyError in __getitem__ return self.__class__(self.items[slc]). What is happening here?


Neither your Stack.__init__ nor your SpecificStack.__init__ take the arguments __getitem__ is passing.

Stack.__init__ doesn’t take any arguments but self, and SpecificStack.__init__ wants an iterable of sequences, but __getitem__ is passing it an iterable of dicts.