| 1 | from reprlib import recursive_repr as _recursive_repr |
| 2 | |
| 3 | class defaultdict(dict): |
| 4 | def __init__(self, *args, **kwargs): |
| 5 | if len(args) >= 1: |
| 6 | default_factory = args[0] |
| 7 | if default_factory is not None and not callable(default_factory): |
| 8 | raise TypeError("first argument must be callable or None") |
| 9 | args = args[1:] |
| 10 | else: |
| 11 | default_factory = None |
| 12 | super().__init__(*args, **kwargs) |
| 13 | self.default_factory = default_factory |
| 14 | |
| 15 | def __missing__(self, key): |
| 16 | if self.default_factory is not None: |
| 17 | val = self.default_factory() |
| 18 | else: |
| 19 | raise KeyError(key) |
| 20 | self[key] = val |
| 21 | return val |
| 22 | |
| 23 | @_recursive_repr() |
| 24 | def __repr_factory(factory): |
| 25 | return repr(factory) |
| 26 | |
| 27 | def __repr__(self): |
| 28 | return f"{type(self).__name__}({defaultdict.__repr_factory(self.default_factory)}, {dict.__repr__(self)})" |
| 29 | |
| 30 | def copy(self): |
| 31 | return type(self)(self.default_factory, self) |
| 32 | |
| 33 | __copy__ = copy |
| 34 | |
| 35 | def __reduce__(self): |
| 36 | if self.default_factory is not None: |
| 37 | args = self.default_factory, |
| 38 | else: |
| 39 | args = () |
| 40 | return type(self), args, None, None, iter(self.items()) |
| 41 | |
| 42 | def __or__(self, other): |
| 43 | if not isinstance(other, dict): |
| 44 | return NotImplemented |
| 45 | |
| 46 | new = defaultdict(self.default_factory, self) |
| 47 | new.update(other) |
| 48 | return new |
| 49 | |
| 50 | def __ror__(self, other): |
| 51 | if not isinstance(other, dict): |
| 52 | return NotImplemented |
| 53 | |
| 54 | new = defaultdict(self.default_factory, other) |
| 55 | new.update(self) |
| 56 | return new |
| 57 | |
| 58 | defaultdict.__module__ = 'collections' |
no outgoing calls