Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python __missing__() Magic Method

#1
Python __missing__() Magic Method

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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2021/12/...ic-method/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

[-]
Discord

[-]
Active Threads
(Indie Deal) Handy Games, Offworld, Citi...
Last Post: xSicKxBot
Yesterday 10:43 AM
» Replies: 0
» Views: 28
News - Pokemon-With-Guns Game Palworld C...
Last Post: xSicKxBot
Yesterday 10:42 AM
» Replies: 0
» Views: 8
(Xbox 360) Mod Forza Horizon 2 with USB
Last Post: tekashisama
Yesterday 02:45 AM
» Replies: 11
» Views: 10533
[Tut] How to Create a NumPy Array and Fi...
Last Post: xSicKxBot
Yesterday 02:45 AM
» Replies: 0
» Views: 29
(Indie Deal) War Giveaways, Akupara, Hum...
Last Post: xSicKxBot
Yesterday 02:45 AM
» Replies: 0
» Views: 11
News - Death’s Gambit: Afterlife Physica...
Last Post: xSicKxBot
Yesterday 02:44 AM
» Replies: 0
» Views: 13
News - Xbox Game Pass Adding Another Day...
Last Post: xSicKxBot
Yesterday 02:44 AM
» Replies: 0
» Views: 16
[Tut] How To Apply A Function To Each El...
Last Post: xSicKxBot
01-26-2022 04:46 PM
» Replies: 0
» Views: 25
(Indie Deal) Exotic Riddles Bundle, Dyin...
Last Post: xSicKxBot
01-26-2022 04:45 PM
» Replies: 0
» Views: 14
Mobile - Pokémon Sword and Shield myster...
Last Post: xSicKxBot
01-26-2022 04:45 PM
» Replies: 0
» Views: 11

[-]
Twitter



Discord Server © SickGaming.net 2012-2021