tags:

views:

137

answers:

1

in pinax Userdict.py:

def __getitem__(self, key):
        if key in self.data:
            return self.data[key]
        if hasattr(self.__class__, "__missing__"):
            return self.__class__.__missing__(self, key)

why does it do this on self.__class__.__missing__.

thanks

+2  A: 

The UserDict.py presented here emulates built-in dict closely, so for example:

>>> class m(dict):
...   def __missing__(self, key): return key + key
... 
>>> a=m()
>>> a['ciao']
'ciaociao'

just as you can override the special method __missing__ to deal with missing keys when you subclass the built-in dict, so can you override it when you subclass that UserDict.

The official Python docs for dict are here, and they do say:

New in version 2.5: If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable. For an example, see collections.defaultdict.

Alex Martelli