'''
DefaultOrderedDict is a combinated OrderedDict and
defaultdict.
'''
from collections import OrderedDict


class DefaultOrderedDict(OrderedDict):
    def __init__(self, default_factory=None):
        OrderedDict.__init__(self)
        self.default_factory = default_factory

    def __getitem__(self, key):
        try:
            return OrderedDict.__getitem__(self, key)
        except KeyError:
            return self.__missing__(key)

    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        self[key] = value = self.default_factory()
        return value

    def __reduce__(self):
        if self.default_factory is None:
            args = tuple()
        else:
            args = (self.default_factory,)
        return type(self), args, None, None, self.items()
