Python __missing__() Magic Method

Rate this post

Syntax

object.__missing__(self, key)

The __missing__(self, key) method defines the behavior of a dictionary subclass if you access a non-existent key. More specifically, Python’s __getitem__() dictionary method internally calls the __missing__() method if the key doesn’t exist. The return value of __missing__() is the value to be returned when trying to access a non-existent 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.

Example

In the following example, you create a dictionary subclass My_Dict_Subclass and overwrite the __missing__() method that simply returns a dummy string 'finxter'.

When trying to access a key that doesn’t exist, Python’s __getitem__() dictionary method internally calls the __missing__() method if the key doesn’t exist.

In our case, the key 'David' doesn’t exist in the dict subclass, so Python calls __missing__() which returns the string 'finxter' instead of raising the KeyError (which would be the default behavior).

class My_Dict_Subclass(dict):
    def __missing__(self, key):
        return 'finxter'



x = {'Alice': 23, 'Bob': 24, 'Carl': 25}
my_dict = My_Dict_Subclass(x)

# Try accessing existing key:
print(my_dict['Bob'])
# 24


# Try accessing missing key:
print(my_dict['David'])
# finxter

If you hadn’t defined the __missing__() method, Python would’ve raised a KeyError.

How to Resolve KeyError on a Dictionary Subclass

Consider the following code snippet where you try to access a non-existent key on a dict subclass.

class My_Dict_Subclass(dict):
    pass


x = {'Alice': 23, 'Bob': 24, 'Carl': 25}
my_dict = My_Dict_Subclass(x)

# Try accessing missing key:
print(my_dict['David'])
# finxter

This results in the following error message on my computer:

Traceback (most recent call last):
  File "C:\Users\...\code.py", line 10, in <module>
    print(my_dict['David'])
KeyError: 'David'

You can fix this by defining the __missing__() method as outlined above—of course, override it with your own desired behavior!

class My_Dict_Subclass(dict):
    def __missing__(self, key):
        return 'finxter'

References:

Related Video

For some additional context, feel free to check out our related video on the dict.get() method that internally calls the dict.__getitem__() method which calls the dict.__missing__() method. Deep shit! 🙂

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!