Source code for spinn_utilities.default_ordered_dict

# Copyright (c) 2019 The University of Manchester
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from collections import OrderedDict
from collections.abc import Callable


[docs]class DefaultOrderedDict(OrderedDict): # Source: https://stackoverflow.com/questions/6190331 def __init__(self, default_factory=None, *args, **kwargs): # pylint: disable=keyword-arg-before-vararg if (default_factory is not None and not isinstance(default_factory, Callable)): raise TypeError('first argument must be callable') super().__init__(*args, **kwargs) self.default_factory = default_factory def __getitem__(self, key): try: return super().__getitem__(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, iter(self.items())
[docs] def copy(self): return type(self)(self.default_factory, self.items())
__copy__ = copy def __deepcopy__(self, memo): import copy return type(self)(self.default_factory, copy.deepcopy(iter(self.items()))) def __repr__(self): return 'DefaultOrderedDict(%s, %s)' % ( self.default_factory, OrderedDict.__repr__(self))