Debian Codegraph @

friendly_traceback/runtime_errors/index_error.py

raw symbols SCIP
1 """Getting specific information for IndexError"""
2
3 import ast
4 import re
5 from typing import Dict
6
7 import pure_eval
8
9 from .. import debug_helper, info_variables
10 from ..ft_gettext import current_lang
11 from ..message_parser import get_parser
12 from ..tb_data import TracebackData # for type checking only
13 from ..typing_info import CauseInfo # for type checking only
14
15 parser = get_parser(IndexError)
16 _ = current_lang.translate
17
18
19 @parser._add
20 def object_assignment_out_of_range(message: str, tb_data: TracebackData) -> CauseInfo:
21 pattern = re.compile(r"(.*) assignment index out of range")
22 match = re.search(pattern, message)
23 if not match:
24 return {}
25
26 obj_type = match[1]
27 frame = tb_data.exception_frame
28 # first, try to identify object
29 left_hand_side = tb_data.bad_line.split("=")[0].strip()
30 all_objects = info_variables.get_all_objects(left_hand_side, frame)
31 for name, sequence in all_objects["name, obj"]:
32 truncated = left_hand_side.replace(name, "", 1).strip()
33 if truncated.startswith("[") and truncated.endswith("]"):
34 break
35 else: # pragma: no cover
36 cause = _(
37 "You have tried to assign a value to an item of an object\n"
38 "of type `{obj_type}` which I cannot identify.\n"
39 "The index you gave was not an allowed value.\n"
40 ).format(obj_type=obj_type)
41 return {"cause": cause}
42
43 index = truncated[1:-1]
44 length = len(sequence)
45
46 cause = _(
47 "You have tried to assign a value to index `{index}` of `{name}`,\n"
48 "{obj_type} of length `{length}`.\n"
49 ).format(
50 index=index,
51 name=name,
52 length=length,
53 obj_type=info_variables.convert_type(obj_type),
54 )
55
56 if length != 0:
57 cause += _(
58 "The valid index values of `{name}` are integers ranging from\n"
59 "`{min}` to `{max}`.\n"
60 ).format(name=name, min=-length, max=length - 1)
61 if index == length:
62 hint = _(
63 "Remember: the first item of {obj_type} is not at index 1 but at index 0.\n"
64 ).format(obj_type=info_variables.convert_type(obj_type))
65 return {"cause": cause, "suggest": hint}
66 else:
67 hint = _("`{name}` contains no item.\n").format(name=name)
68 cause = _(
69 "You have tried to assign a value to index `{index}` of `{name}`,\n"
70 "{obj_type} which contains no item.\n"
71 ).format(index=index, name=name, obj_type=info_variables.convert_type(obj_type))
72 return {"cause": cause, "suggest": hint}
73
74 return {"cause": cause}
75
76
77 def cannot_identify_object(obj_type: str, bad_line: str) -> Dict:
78 message = f"Cannot identify `{obj_type}` object. line: {bad_line}"
79 debug_helper.log(message)
80 cause = _(
81 "You have tried to get an item of an object\n"
82 "of type `{obj_type}` which I cannot identify.\n"
83 "The index you gave was not an allowed value.\n"
84 ).format(obj_type=obj_type)
85 return {"cause": cause}
86
87
88 @parser._add
89 def index_out_of_range(message: str, tb_data: TracebackData) -> CauseInfo:
90 pattern = re.compile(r"(.*) index out of range")
91 match = re.search(pattern, message)
92 if not match:
93 return {}
94
95 obj_type = match[1]
96 frame = tb_data.exception_frame
97 bad_line = tb_data.bad_line
98 # first, try to identify object
99 all_objects = info_variables.get_all_objects(bad_line, frame)
100 for name, sequence in all_objects["name, obj"]:
101 truncated = bad_line.replace(name, "", 1).strip()
102 if truncated.startswith("[") and truncated.endswith("]"):
103 break
104 else: # pragma: no cover
105 return cannot_identify_object(obj_type, bad_line)
106
107 try:
108 node = tb_data.node
109 except Exception: # noqa # pragma: no cover
110 return cannot_identify_object(obj_type, bad_line)
111
112 if not (node and isinstance(node, ast.Subscript)): # pragma: no cover
113 return cannot_identify_object(obj_type, bad_line)
114
115 length = len(sequence)
116 evaluator = pure_eval.Evaluator.from_frame(frame)
117 # The information that we want may differ for different Python versions
118 try:
119 index = evaluator[node.slice.value] # noqa
120 except Exception: # noqa
121 try:
122 index = evaluator[node.slice]
123 except Exception: # noqa # pragma: no cover
124 debug_helper.log("Unknown index: new case to consider.")
125 cause = _(
126 "You have tried to get an item from `{name}`,\n"
127 "{obj_type} of length `{length}`, by using a value for the index\n"
128 "that I cannot determine but which is not allowed.\n"
129 ).format(
130 name=name, length=length, obj_type=info_variables.convert_type(obj_type)
131 )
132 return {"cause": cause}
133
134 cause = _(
135 "You have tried to get the item with index `{index}` of `{name}`,\n"
136 "{obj_type} of length `{length}`.\n"
137 ).format(
138 index=index,
139 name=name,
140 length=length,
141 obj_type=info_variables.convert_type(obj_type),
142 )
143
144 if length != 0:
145 cause += _(
146 "The valid index values of `{name}` are integers ranging from\n"
147 "`{min}` to `{max}`.\n"
148 ).format(name=name, min=-length, max=length - 1)
149 if index == length:
150 hint = _(
151 "Remember: the first item of {obj_type} is not at index 1 but at index 0.\n"
152 ).format(obj_type=info_variables.convert_type(obj_type))
153 return {"cause": cause, "suggest": hint}
154 else:
155 hint = _("`{name}` contains no item.\n").format(name=name)
156 cause = _(
157 "You have tried to get the item with index `{index}` of `{name}`,\n"
158 "{obj_type} which contains no item.\n"
159 ).format(index=index, name=name, obj_type=info_variables.convert_type(obj_type))
160 return {"cause": cause, "suggest": hint}
161
162 return {"cause": cause}