Python __getitem__() Magic Method

5/5 - (4 votes)

Python’s magic method __getitem__(self, key) to evaluate the expression self[key]. So, if you call my_obj[key], Python will call my_obj.__getitem__(key).

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

Syntax and Minimal Example

object.__getitem__(self, key)

Let’s have a look at an example where you override the __getitem__ magic method of a custom class HelloWorld.

class HelloWorld:
    def __getitem__(self, key):
        print('hello world', key)

hi = HelloWorld()

# hello world 42

hi['wide web']
# hello world wide web

This code shows several interesting things:

  • You use obj[key] to call obj.__getitem__(key).
  • You can pass arbitrary keys into it.
  • You don’t even need to return anything from __getitem__ (although it’s of course not recommended). In this case, None is returned.

However, this is just a dummy example, let’s have a look at a full example implementing all methods __getitem__, __setitem__, and __delitem__ that together play together beautifully to implement a collection-like custom data type.

Full Example

In the following example, you create a custom list-like type that overrides the __getitem__, __setitem__, and __delitem__ methods.

class MyList:
    def __init__(self, lst):
        self.lst = lst

    def __getitem__(self, key):
        print('__getitem__', key)
        return self.lst[key]

    def __setitem__(self, key, value):
        print('__setitem__', key, value)
        self.lst[key] = value

    def __delitem__(self, key):
        print('__delitem__', key)
        del self.lst[key]

Each time you add a new element, get an element, or delete an element from your custom list, it prints the respective information so you see what happens.

Now, let’s use this to create a simple list wrapper and print the second element with index 1 (zero-based indexing).

my = MyList(['alice', 'bob', 'carl'])

# __getitem__ 1
# bob

Note how Python first calls the print statement within the __getitem__ output and key 1 and then returns the element my[1] itself, puts it into the print(...) statement which results in the output bob.

Next, you overwrite the value of the second list element with index 1:

my[1] = '42'
# __setitem__ 1 42
# __getitem__ 1
# 42

You can see from the print output __setitem__ 1 42 that __setitem__ was called with key 1 and value 42.

Next, you delete an element with the expression del my[1]:

del my[1]
# carl


Where to Go From Here?

Enough theory. Letโ€™s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. Thatโ€™s how you polish the skills you really need in practice. After all, whatโ€™s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

๐Ÿš€ If your answer is YES!, consider becoming a Python freelance developer! Itโ€™s the best way of approaching the task of improving your Python skillsโ€”even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar โ€œHow to Build Your High-Income Skill Pythonโ€ and learn how I grew my coding business online and how you can, tooโ€”from the comfort of your own home.

Join the free webinar now!