__getitem__ in Python

The __getitem__ method is a special method in Python that plays a crucial role in how objects can be accessed using the bracket notation, similar to how elements in lists or dictionaries are accessed. This method allows for defining custom behavior for element access within a class, making objects iterable and compatible with for loops.

Overview

The __getitem__ method is invoked when an instance of a class is accessed using the subscript notation, such as instance[index]. This method is essential for enabling objects to behave like sequences, allowing them to be accessed by index. When implementing __getitem__, it is important to handle the scenario where the end of the sequence is reached by raising an IndexError.

Definition

The basic definition of the __getitem__ method is as follows:

def __getitem__(self, i):
    return self.elements[i]

In this example, self.elements is assumed to be a list or another sequence type, and the method returns the element at the specified index i.

Example: LineReader Class

To illustrate the use of __getitem__, consider the LineReader class, which reads lines from a file and allows iteration over them:

class LineReader:
    def __init__(self, filename):
        self.fileobject = open(filename, 'r')              #A
    def __getitem__(self, index):
        line = self.fileobject.readline()                  #B
        if line == "":                                #C
             self.fileobject.close()      #D
            raise IndexError         #E
            
        else:
            return line.split("::")[:2]                    #F
 
for name, age in LineReader("filename"):
    . . . do whatever . . .
#A Opens file for reading
#B Tries to read line
#C If no more data …
#D … closes fileobject …
#E … and raises IndexError
#F Otherwise, splits line, returns first two fields

Explanation

  • Opening the File: The LineReader class opens a file for reading when an instance is created (#A).
  • Reading Lines: The __getitem__ method attempts to read a line from the file (#B).
  • End of File Handling: If the end of the file is reached (indicated by an empty string), the file is closed, and an IndexError is raised (#C, #D, #E).
  • Returning Data: If a line is successfully read, it is split into fields, and the first two fields are returned (#F).

By implementing the __getitem__() method in this way, instances of the LineReader class can be used as iterables in a for loop, reading a line of the file with each iteration. The method raises an IndexError to signal the end of the file, allowing the loop to terminate gracefully.