-
Book Overview & Buying
-
Table Of Contents
Secret Recipes of the Python Ninja
By :
Another dictionary subclass, defaultdict calls a factory function to provide missing values; basically, it creates any items that you try to access, but only if they don't currently exist. This way, you don't get KeyError when trying to access a non-existent key.
All the standard dictionary methods are available, as well as the following:
__missing__(key): This method is used by the dict class __getitem__() method when the requested key is not found. Whatever key it returns (or an exception if no key is present) is passed to __getitem__(), which processes it accordingly.
Assuming the default_factory is not None, this method calls the factory to receive a default value for key, which is then placed in the dictionary as the key, and then returns back to the caller. If the factory value is None, then an exception is thrown with the key as the argument. If the default_factory raises an exception on its own, then the exception is passed along unaltered.
The __missing__()...