liveBook · Manning

__getitem__

As explained in The Quick Python Book, Fourth Edition

__getitem__ is a Python special method that defines how an object responds when an item or slice is accessed with subscription syntax.

Define `__getitem__` in a class to control what happens when an instance is accessed with subscription syntax. For an object `obj`, `obj[i]` invokes `obj.__getitem__(i)`. The method receives the index and returns the value to be accessed. section 17.7.1

An object with `__getitem__` can also be used in a `for` loop through successive accesses at indexes 0, 1, 2, and so on. Raising `IndexError` tells that loop to stop. This makes sequential access possible without storing every item in a list. section 17.7 section 17.7.1

class LineReader:
    def __init__(self, filename):
        self.fileobject = open(filename, 'r')        #1
    def __getitem__(self, index):
        line = self.fileobject.readline()            #2
        if line == "":                               #3
            self.fileobject.close()                  #4
            raise IndexError                         #5
            
        else:
            return line.split("::")[:2]              #6
 
for name, age in LineReader("filename"):
    . . . do whatever . . .

`LineReader` reads one file line per access. It deliberately ignores the index, closes the file at the end, and raises `IndexError` to end the loop. section 17.7 section 17.7.1

Ignoring the index works for that narrow, sequential use; it does not provide general list behavior. An index-aware implementation can instead return an element from an underlying list. Other operations need their own special methods: `__setitem__`, for example, handles `obj[i] = value`. section 17.7.2 section 17.8

class TypedList:
   def __init__(self, example_element, initial_list=[]):
       self.type = type(example_element)
       if not isinstance(initial_list, list):
           raise TypeError("Second argument of TypedList must " 
                           "be a list.")
       for element in initial_list: 
           self.__check(element)
       self.elements = initial_list[:]
   def __check(self, element):
       if type(element) != self.type:
           raise TypeError("Attempted to add an element of " 
                           "incorrect type to a typed list.")
   def __setitem__(self, i, element):
       self.__check(element)
       self.elements[i] = element
   def __getitem__(self, i):
       return self.elements[i]

`TypedList.__getitem__` passes the index to its stored list, while `__setitem__` checks an element’s type before assignment. section 17.8

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains subscription dispatch, sequential iteration, and `IndexError` termination, then contrasts narrow iteration with index-aware list behavior.
Examples
Uses a line-by-line file reader and a type-checked list backed by a regular list.
What it assumes
Assumes familiarity with classes and loops while explaining how subscription becomes a method call.
What you can do after
Build it from scratch: define indexed access for a class and use `IndexError` to end sequential iteration.
How it connects
Connects subscription to special methods, `for` loops, `IndexError`, `__setitem__`, and list emulation.

Also explained in

Compare how 2 books explain __getitem__ →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.