Python `__getitem__`: Custom logic behind square brackets

Python `__getitem__`: Custom logic behind square brackets

The __getitem__ method in Python can do more than simple lookups:

class DoubleIndex:
    def __getitem__(self, i):
        return i * 2
d = DoubleIndex()
d[5]  # returns 10

Use [] for custom logic — returning filenames, random numbers, or database records.