| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
import _collections |
| 11 |
|
| 12 |
|
| 13 |
class defaultdict(dict): |
| 14 |
__slots__ = ['default_factory'] |
| 15 |
__module__ = 'collections' |
| 16 |
|
| 17 |
def __init__(self, *args, **kwds): |
| 18 |
if len(args) > 0: |
| 19 |
default_factory = args[0] |
| 20 |
args = args[1:] |
| 21 |
if not callable(default_factory) and default_factory is not None: |
| 22 |
raise TypeError("first argument must be callable") |
| 23 |
else: |
| 24 |
default_factory = None |
| 25 |
defaultdict.default_factory.__set__(self, default_factory) |
| 26 |
super(defaultdict, self).__init__(*args, **kwds) |
| 27 |
|
| 28 |
def __missing__(self, key): |
| 29 |
pass |
| 30 |
__missing__.__code__ = _collections.__missing__.__code__ |
| 31 |
|
| 32 |
def __repr__(self, recurse=set()): |
| 33 |
|
| 34 |
dictrepr = super(defaultdict, self).__repr__() |
| 35 |
if id(self) in recurse: |
| 36 |
factoryrepr = "..." |
| 37 |
else: |
| 38 |
try: |
| 39 |
recurse.add(id(self)) |
| 40 |
factoryrepr = repr(self.default_factory) |
| 41 |
finally: |
| 42 |
recurse.remove(id(self)) |
| 43 |
return "%s(%s, %s)" % (self.__class__.__name__, factoryrepr, dictrepr) |
| 44 |
|
| 45 |
def copy(self): |
| 46 |
return type(self)(self.default_factory, self) |
| 47 |
|
| 48 |
__copy__ = copy |
| 49 |
|
| 50 |
def __reduce__(self): |
| 51 |
""" |
| 52 |
__reduce__ must return a 5-tuple as follows: |
| 53 |
|
| 54 |
- factory function |
| 55 |
- tuple of args for the factory function |
| 56 |
- additional state (here None) |
| 57 |
- sequence iterator (here None) |
| 58 |
- dictionary iterator (yielding successive (key, value) pairs |
| 59 |
|
| 60 |
This API is used by pickle.py and copy.py. |
| 61 |
""" |
| 62 |
return (type(self), (self.default_factory,), None, None, |
| 63 |
iter(self.items())) |
| 64 |
|
| 65 |
def __or__(self, other): |
| 66 |
if not isinstance(other, dict): |
| 67 |
return NotImplemented |
| 68 |
copyself = self.copy() |
| 69 |
copyself.update(other) |
| 70 |
return copyself |
| 71 |
|
| 72 |
def __ror__(self, other): |
| 73 |
if not isinstance(other, dict): |
| 74 |
return NotImplemented |
| 75 |
res = type(self)(self.default_factory, other) |
| 76 |
res.update(self) |
| 77 |
return res |
| 78 |
|
| 79 |
|