|
| 1 | +"""StrKeyDict always converts non-string keys to `str` |
| 2 | +
|
| 3 | +This is a variation of `strkeydict.StrKeyDict` implemented |
| 4 | +as a `dict` built-in subclass (instead of a `UserDict` subclass) |
| 5 | +
|
| 6 | +Test for initializer: keys are converted to `str`. |
| 7 | +
|
| 8 | + >>> d = StrKeyDict([(2, 'two'), ('4', 'four')]) |
| 9 | + >>> sorted(d.keys()) |
| 10 | + ['2', '4'] |
| 11 | +
|
| 12 | +Tests for item retrieval using `d[key]` notation:: |
| 13 | +
|
| 14 | + >>> d['2'] |
| 15 | + 'two' |
| 16 | + >>> d[4] |
| 17 | + 'four' |
| 18 | + >>> d[1] |
| 19 | + Traceback (most recent call last): |
| 20 | + ... |
| 21 | + KeyError: '1' |
| 22 | +
|
| 23 | +Tests for item retrieval using `d.get(key)` notation:: |
| 24 | +
|
| 25 | + >>> d.get('2') |
| 26 | + 'two' |
| 27 | + >>> d.get(4) |
| 28 | + 'four' |
| 29 | + >>> d.get(1, 'N/A') |
| 30 | + 'N/A' |
| 31 | +
|
| 32 | +Tests for the `in` operator:: |
| 33 | +
|
| 34 | + >>> 2 in d |
| 35 | + True |
| 36 | + >>> 1 in d |
| 37 | + False |
| 38 | +
|
| 39 | +Test for item assignment using non-string key:: |
| 40 | +
|
| 41 | + >>> d[0] = 'zero' |
| 42 | + >>> d['0'] |
| 43 | + 'zero' |
| 44 | +
|
| 45 | +Tests for update using a `dict` or a sequence of pairs:: |
| 46 | +
|
| 47 | + >>> d.update({6:'six', '8':'eight'}) |
| 48 | + >>> sorted(d.keys()) |
| 49 | + ['0', '2', '4', '6', '8'] |
| 50 | + >>> d.update([(10, 'ten'), ('12', 'twelve')]) |
| 51 | + >>> sorted(d.keys()) |
| 52 | + ['0', '10', '12', '2', '4', '6', '8'] |
| 53 | + >>> d.update([1, 3, 5]) |
| 54 | + Traceback (most recent call last): |
| 55 | + ... |
| 56 | + TypeError: cannot unpack non-iterable int object |
| 57 | +
|
| 58 | +""" |
| 59 | + |
| 60 | + |
| 61 | +class StrKeyDict(dict): |
| 62 | + |
| 63 | + def __init__(self, iterable=None, **kwds): |
| 64 | + super().__init__() |
| 65 | + self.update(iterable, **kwds) |
| 66 | + |
| 67 | + def __missing__(self, key): |
| 68 | + if isinstance(key, str): |
| 69 | + raise KeyError(key) |
| 70 | + return self[str(key)] |
| 71 | + |
| 72 | + def __contains__(self, key): |
| 73 | + return key in self.keys() or str(key) in self.keys() |
| 74 | + |
| 75 | + def __setitem__(self, key, item): |
| 76 | + super().__setitem__(str(key), item) |
| 77 | + |
| 78 | + def get(self, key, default=None): |
| 79 | + try: |
| 80 | + return self[key] |
| 81 | + except KeyError: |
| 82 | + return default |
| 83 | + |
| 84 | + def update(self, iterable=None, **kwds): |
| 85 | + if iterable is not None: |
| 86 | + try: # duck typing FTW! |
| 87 | + pairs = iterable.items() |
| 88 | + except AttributeError: |
| 89 | + pairs = iterable |
| 90 | + for key, value in pairs: |
| 91 | + self[key] = value |
| 92 | + if kwds: |
| 93 | + self.update(kwds) |
0 commit comments