这是我现在使用的解决方案,因为我们不能覆盖内置的。
class LXKeyError(KeyError):
def __init__(self, item, d):
self.item = item
self.d = d
def __str__(self):
keys = str(list(self.d.keys()))
if len(keys) > 1000: # (13 (max field length in uf) + 4 ("', '")) * 50 (max number of fields we want to print) = 850
keys = f'{keys[:995]} ...'
return f'Unknown key in dict: {self.item!r} (keys: {keys})'
class LXDict(dict):
def __missing__(self, key):
raise LXKeyError(key, self)
orig_d = {'a': 'a', 'b': 'b', '1': '', '2': '', '3': '', '4': '', '5': '', '6': '', '7': '', '8': '', '9': '', '10': '', '11': '', '12': '',
'13': '', '14': '', '15': '', '16': '', '17': '', '18': '', '19': '', '20': '',
}
d = LXDict(orig_d)
try:
d['x']
assert False, f'Should not arrive here'
except KeyError as ex:
print(ex)