| 1 |
import ast |
| 2 |
from types import FrameType |
| 3 |
from typing import Any, Optional, Tuple |
| 4 |
|
| 5 |
from .. import info_variables, utils |
| 6 |
from ..ft_gettext import current_lang, please_report |
| 7 |
from ..message_parser import get_parser |
| 8 |
from ..tb_data import TracebackData |
| 9 |
from ..typing_info import CauseInfo |
| 10 |
|
| 11 |
parser = get_parser(KeyError) |
| 12 |
_ = current_lang.translate |
| 13 |
|
| 14 |
|
| 15 |
@parser._add |
| 16 |
def popitem_from_empty_dict(message: str, tb_data: TracebackData) -> CauseInfo: |
| 17 |
if "popitem(): dictionary is empty" not in message: |
| 18 |
return {} |
| 19 |
|
| 20 |
frame = tb_data.exception_frame |
| 21 |
name, _obj = find_empty_dict_like_obj(frame, tb_data.bad_line) |
| 22 |
if name is None: |
| 23 |
cause = _( |
| 24 |
"You tried to retrieve an item from an empty `dict`\n" |
| 25 |
"or a similar object which I cannot identify.\n" |
| 26 |
) |
| 27 |
return {"cause": cause + please_report()} |
| 28 |
|
| 29 |
hint = _("`{name}` is an empty `dict`.\n").format(name=name) |
| 30 |
cause = _( |
| 31 |
"You tried to retrieve an item from `{name}` which is an empty `dict`.\n" |
| 32 |
).format(name=name) |
| 33 |
return {"cause": cause, "suggest": hint} |
| 34 |
|
| 35 |
|
| 36 |
@parser._add |
| 37 |
def popitem_from_empty_chain_map(message: str, tb_data: TracebackData) -> CauseInfo: |
| 38 |
if "No keys found in the first mapping." not in message: |
| 39 |
return {} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
name, _obj = find_empty_dict_like_obj( |
| 46 |
tb_data.program_stopped_frame, tb_data.program_stopped_bad_line |
| 47 |
) |
| 48 |
if name is None: |
| 49 |
cause = _( |
| 50 |
"You tried to retrieve an item from an empty ChainMap\n" |
| 51 |
"or similar object which I cannot identify.\n" |
| 52 |
) |
| 53 |
return {"cause": cause + please_report()} |
| 54 |
|
| 55 |
hint = _("`{name}` is an empty `ChainMap`.\n").format(name=name) |
| 56 |
cause = _( |
| 57 |
"You tried to retrieve an item from `{name}` which is an empty `ChainMap`.\n" |
| 58 |
).format(name=name) |
| 59 |
return {"cause": cause, "suggest": hint} |
| 60 |
|
| 61 |
|
| 62 |
@parser._add |
| 63 |
def missing_key_in_chain_map(message: str, tb_data: TracebackData) -> CauseInfo: |
| 64 |
"""Missing keys in collections.ChainMap from using pop() |
| 65 |
can trigger a secondary exception with a different message. |
| 66 |
It turns out that this is this second message we capture |
| 67 |
while the correct "bad_line" is identified correctly. |
| 68 |
""" |
| 69 |
if "Key not found in the first mapping: " not in message: |
| 70 |
return {} |
| 71 |
|
| 72 |
frame = tb_data.exception_frame |
| 73 |
value = tb_data.value |
| 74 |
key = value.args[0] |
| 75 |
if not ( |
| 76 |
isinstance(key, str) and key.startswith("Key not found in the first mapping: ") |
| 77 |
): |
| 78 |
return {} |
| 79 |
|
| 80 |
key = key.replace("Key not found in the first mapping: ", "", 1) |
| 81 |
try: |
| 82 |
key = ast.literal_eval(key) |
| 83 |
except Exception: |
| 84 |
pass |
| 85 |
|
| 86 |
bad_line = tb_data.bad_line.strip() |
| 87 |
if bad_line.startswith("raise "): |
| 88 |
bad_line = tb_data.program_stopped_bad_line.strip() |
| 89 |
frame = tb_data.program_stopped_frame |
| 90 |
|
| 91 |
if str(key) in bad_line: |
| 92 |
cause = analyze_missing_key(key, frame, bad_line) |
| 93 |
if cause: |
| 94 |
return cause |
| 95 |
|
| 96 |
return { |
| 97 |
"cause": _( |
| 98 |
"Missing key `{key}` in a `ChainMap` or in a similar object.\n" |
| 99 |
).format(key=key) |
| 100 |
} |
| 101 |
|
| 102 |
|
| 103 |
@parser._add |
| 104 |
def missing_key_in_dict(_message: str, tb_data: TracebackData) -> CauseInfo: |
| 105 |
value = tb_data.value |
| 106 |
bad_line = tb_data.bad_line.strip() |
| 107 |
frame = tb_data.exception_frame |
| 108 |
if bad_line.startswith("raise "): |
| 109 |
return {} |
| 110 |
key = value.args[0] |
| 111 |
return {} if str(key) not in bad_line else analyze_missing_key(key, frame, bad_line) |
| 112 |
|
| 113 |
|
| 114 |
@parser._add |
| 115 |
def missing_key_in_dict_like(_message: str, tb_data: TracebackData) -> CauseInfo: |
| 116 |
"""Case where a KeyError is raised internally, from user code""" |
| 117 |
value = tb_data.value |
| 118 |
key = value.args[0] |
| 119 |
bad_line = tb_data.bad_line.strip() |
| 120 |
if not bad_line.startswith("raise "): |
| 121 |
return {} |
| 122 |
bad_line = tb_data.program_stopped_bad_line |
| 123 |
if str(key) not in bad_line: |
| 124 |
return {} |
| 125 |
frame = tb_data.program_stopped_frame |
| 126 |
|
| 127 |
return analyze_missing_key(key, frame, bad_line) |
| 128 |
|
| 129 |
|
| 130 |
def analyze_missing_key(key: Any, frame: FrameType, bad_line: str) -> CauseInfo: |
| 131 |
name, obj = find_missing_key_obj(key, frame, bad_line) |
| 132 |
try: |
| 133 |
key_repr = repr(key) |
| 134 |
except Exception: |
| 135 |
return {} |
| 136 |
if name is None: |
| 137 |
cause = _( |
| 138 |
"A `dict` or a similar object which I cannot identify\n" |
| 139 |
"does not have `{key}` as a key.\n" |
| 140 |
).format(key=key_repr) |
| 141 |
return {"cause": cause} |
| 142 |
|
| 143 |
if isinstance(obj, dict): |
| 144 |
begin_cause = _( |
| 145 |
"The key `{key}` cannot be found in the dict `{name}`.\n" |
| 146 |
).format(key=key_repr, name=name) |
| 147 |
else: |
| 148 |
obj_type = obj.__class__.__name__ |
| 149 |
begin_cause = _( |
| 150 |
"The key `{key}` cannot be found in `{name}`, an object of type `{obj_type}`.\n" |
| 151 |
).format(key=key_repr, name=name, obj_type=obj_type) |
| 152 |
|
| 153 |
if isinstance(key, str): |
| 154 |
result = key_is_a_string(key, name, obj) |
| 155 |
if result: |
| 156 |
result["cause"] = begin_cause + result["cause"] |
| 157 |
return result |
| 158 |
elif str(key) in obj.keys(): |
| 159 |
additional = _( |
| 160 |
"`{name}` contains a string key which is identical to `str({key})`.\n" |
| 161 |
"Perhaps you forgot to convert the key into a string.\n" |
| 162 |
).format(name=name, key=key) |
| 163 |
hint = _("Did you forget to convert `{key}` into a string?\n").format(key=key) |
| 164 |
return {"cause": begin_cause + additional, "suggest": hint} |
| 165 |
|
| 166 |
return {"cause": begin_cause} |
| 167 |
|
| 168 |
|
| 169 |
def key_is_a_string(key: str, dict_name: str, obj: Any) -> CauseInfo: |
| 170 |
keys = [str(k) for k in obj.keys()] |
| 171 |
if key in keys: |
| 172 |
additional = _( |
| 173 |
"`{key}` is a string.\n" |
| 174 |
"There is a key of `{name}` whose string representation\n" |
| 175 |
"is identical to `{key}`.\n" |
| 176 |
).format(key=repr(key), name=dict_name) |
| 177 |
hint = _("Did you convert `{key}` into a string by mistake?\n").format(key=key) |
| 178 |
return {"cause": additional, "suggest": hint} |
| 179 |
|
| 180 |
string_keys = [k for k in obj.keys() if isinstance(k, str)] |
| 181 |
similar = utils.get_similar_words(key, string_keys) |
| 182 |
similar = [repr(k) for k in similar] |
| 183 |
if len(similar) == 1: |
| 184 |
hint = _("Did you mean `{name}`?\n").format(name=similar[0]) |
| 185 |
additional = _( |
| 186 |
"`{name}` is a key of `{dict_}` which is similar to `{key}`.\n" |
| 187 |
).format(name=similar[0], dict_=dict_name, key=repr(key)) |
| 188 |
return {"cause": additional, "suggest": hint} |
| 189 |
|
| 190 |
if similar: |
| 191 |
hint = _("Did you mean `{name}`?\n").format(name=similar[0]) |
| 192 |
names = ", ".join(similar) |
| 193 |
additional = _( |
| 194 |
"`{name}` has some keys similar to `{key}` including:\n`{names}`.\n" |
| 195 |
).format(name=dict_name, key=repr(key), names=names) |
| 196 |
return {"cause": additional, "suggest": hint} |
| 197 |
|
| 198 |
return {} |
| 199 |
|
| 200 |
|
| 201 |
def find_empty_dict_like_obj( |
| 202 |
frame: FrameType, bad_line: str |
| 203 |
) -> Tuple[Optional[str], Any]: |
| 204 |
all_objects = info_variables.get_all_objects(bad_line, frame) |
| 205 |
for name, obj in all_objects["name, obj"]: |
| 206 |
if hasattr(obj, "keys") and len(obj) == 0: |
| 207 |
return name, obj |
| 208 |
return None, None |
| 209 |
|
| 210 |
|
| 211 |
def find_missing_key_obj( |
| 212 |
key: Any, frame: FrameType, bad_line: str |
| 213 |
) -> Tuple[Optional[str], Any]: |
| 214 |
all_objects = info_variables.get_all_objects(bad_line, frame) |
| 215 |
for name, obj in all_objects["name, obj"]: |
| 216 |
if hasattr(obj, "keys") and key not in obj: |
| 217 |
return name, obj |
| 218 |
return None, None |