Implementing defaultdict
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 thedict
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 notNone
, this method calls the factory to receive a default value forkey
, which is then placed in the dictionary as thekey
, and then returns back to the caller. If the factory value isNone
, then an exception is thrown with thekey
as the argument. If thedefault_factory
raises an exception on its own, then the exception is passed along unaltered.The
__missing__()
...