Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call __missing__ from dict

I would like to derive from dict and overwrite the method missing. I would like to do some stuff and then still call its super function. Something like this:

class Foo(dict):
    def __missing__(self, key):
        print('missing {}'.format(key))
        return super().__missing__(key)

Which however produces:

AttributeError: 'super' object has no attribute '__missing__'

Of course I could still make a working program using:

raise KeyError(key)

But I would much rather call the super function. Because code could (or maybe at a future version of python will be) executed in super().__missing__ other than raising the KeyError.

like image 784
magu_ Avatar asked Feb 07 '23 23:02

magu_


1 Answers

There is no dict.__missing__; just drop the call to super().__missing__ (and raise a KeyError). The method is optional and has no default implementation.

Alternatively, if you want to support multiple inheritance properly, you could catch the AttributeError exception:

class Foo(dict):
    def __missing__(self, key):
        print('missing {}'.format(key))
        try:
            return super().__missing__(key)
        except AttributeError:
            raise KeyError(key)
like image 118
Martijn Pieters Avatar answered Feb 10 '23 12:02

Martijn Pieters