Debian Codegraph @

friendly_traceback/runtime_errors/value_error.py

raw symbols SCIP
1 """value_error.py
2
3 Collection of functions useful in parsing ValueError messages and
4 providing a more detailed explanation.
5 """
6
7 import inspect
8 import re
9 import unicodedata
10 from types import FrameType
11 from typing import Any, Optional, Tuple
12
13 from .. import debug_helper, info_variables, token_utils, utils
14 from ..ft_gettext import current_lang
15 from ..message_parser import get_parser
16 from ..tb_data import TracebackData # for type checking only
17 from ..typing_info import CauseInfo # for type checking only
18
19 convert_type = info_variables.convert_type
20 parser = get_parser(ValueError)
21 _ = current_lang.translate
22
23
24 def _unpacking() -> str:
25 return _(
26 "Unpacking is a convenient way to assign a name,\n"
27 "to each item of an iterable.\n"
28 )
29
30
31 def get_iterable(code: str, frame: FrameType) -> Tuple[Any, Optional[str]]:
32 """gets an iterable object and its type as a string."""
33 try:
34 # As a ValueError exception has been raised, Python has already evaluated
35 # all the relevant code parts. Thus, using eval should be completely safe.
36 obj = utils.eval_expr(code, frame)
37 except Exception: # noqa
38 return None, None
39
40 if isinstance(obj, dict):
41 iterable = "dict"
42 elif isinstance(obj, list):
43 iterable = "list"
44 elif isinstance(obj, set):
45 iterable = "set"
46 elif isinstance(obj, str):
47 iterable = "str"
48 elif isinstance(obj, tuple):
49 iterable = "tuple"
50 else:
51 iterable = None
52 return obj, iterable
53
54
55 @parser._add
56 def not_enough_values_to_unpack(message: str, tb_data: TracebackData) -> CauseInfo:
57 pattern1 = re.compile(r"not enough values to unpack \(expected (\d+), got (\d+)\)")
58 match1 = re.search(pattern1, message)
59 pattern2 = re.compile(
60 r"not enough values to unpack \(expected at least (\d+), got (\d+)\)"
61 )
62 match2 = re.search(pattern2, message)
63 if match1 is None and match2 is None:
64 return {}
65
66 match = match1 if match2 is None else match2
67 frame = tb_data.exception_frame
68 nb_names = match[1]
69 length = match[2]
70
71 if tb_data.bad_line.count("=") != 1:
72 cause = _unpacking() + _(
73 "In this instance, there are more names ({nb_names})\n"
74 "than {length}, the length of the iterable.\n"
75 ).format(nb_names=nb_names, length=length)
76 return {"cause": cause}
77
78 _lhs, rhs = tb_data.bad_line.split("=")
79 obj, iterable = get_iterable(rhs, frame)
80 if obj is None or iterable is None:
81 cause = _unpacking() + _(
82 "In this instance, there are more names ({nb_names})\n"
83 "than {length}, the length of the iterable.\n"
84 ).format(nb_names=nb_names, length=length)
85 return {"cause": cause}
86
87 cause = _unpacking() + _(
88 "In this instance, there are more names ({nb_names})\n"
89 "than the length of the iterable, {iter_type} of length {length}.\n"
90 ).format(nb_names=nb_names, iter_type=convert_type(iterable), length=length)
91 return {"cause": cause}
92
93
94 @parser._add
95 def too_many_values_to_unpack(message: str, tb_data: TracebackData) -> CauseInfo:
96 pattern = re.compile(r"too many values to unpack \(expected (\d+)\)")
97 match = re.search(pattern, message)
98 if match is None:
99 return {}
100
101 nb_names = match[1]
102 frame = tb_data.exception_frame
103
104 if tb_data.bad_line.count("=") != 1:
105 cause = _unpacking() + _(
106 "In this instance, there are fewer names ({nb_names})\n"
107 "than the length of the iterable.\n"
108 ).format(nb_names=nb_names)
109 return {"cause": cause}
110
111 _lhs, rhs = tb_data.bad_line.split("=")
112
113 obj, iterable = get_iterable(rhs, frame)
114 if obj is None or iterable is None or not hasattr(obj, "__len__"):
115 cause = _unpacking() + _(
116 "In this instance, there are fewer names ({nb_names})\n"
117 "than the length of the iterable.\n"
118 ).format(nb_names=nb_names)
119 return {"cause": cause}
120
121 cause = _unpacking() + _(
122 "In this instance, there are fewer names ({nb_names})\n"
123 "than the length of the iterable, {iter_type} of length {length}.\n"
124 ).format(nb_names=nb_names, iter_type=convert_type(iterable), length=len(obj))
125 return {"cause": cause}
126
127
128 @parser._add
129 def invalid_literal_for_int(message: str, _tb_data: TracebackData) -> CauseInfo:
130 pattern = re.compile(r"invalid literal for int\(\) with base (\d+): '(.*)'")
131 match = re.search(pattern, message)
132 if match is None:
133 return {}
134
135 base, value = int(match[1]), match[2]
136 if not value.strip():
137 cause = _(
138 "`int()` expects an argument that looks like a number in base `{base}`\n"
139 "but you gave it an empty string.\n"
140 ).format(base=base)
141 return {"cause": cause}
142
143 begin_cause = _(
144 "`{value}` is an invalid argument for `int()` in base `{base}`.\n"
145 ).format(value=repr(value), base=base)
146
147 valid = "0123456789abcdefghijiklmnopqrstuvwxyz"[:base]
148 invalid = []
149 for index, char in enumerate(value.strip()):
150 if index == 0 and char in ["+", "-"]:
151 continue
152 if char.isalpha():
153 convert = char.lower()
154 else:
155 convert = unicodedata.numeric(char, None)
156 convert = str(int(convert)) if convert is not None else char
157 if convert not in valid and char not in invalid:
158 invalid.append(char)
159 invalid = _("The following characters are not allowed: `{invalid}`.\n").format(
160 invalid=utils.list_to_string(invalid)
161 )
162 if base == 10:
163 try:
164 int(float(value))
165 except ValueError:
166 pass
167 else:
168 return _convert_to_float(value)
169
170 if base == 0:
171 cause = _(
172 "When base `0` is specified, `int()` expects the argument\n"
173 "to be an integer literal, written in\n"
174 "base 2 (`0b...`), 8 (`0o...`), 10, or 16 (`0x...`).\n"
175 )
176 elif 2 <= base <= 10:
177 cause = _(
178 "In base `{base}`, `int()` is most often use to convert a string\n"
179 "containing the digits `0` to `{max_n}` into an integer.\n"
180 ).format(base=base, max_n=valid[base - 1])
181 elif base == 11:
182 cause = _(
183 "In base `11`, `int()` is most often use to convert a string\n"
184 "containing the digits `0` to `9` and the letter `'a'` into an integer.\n"
185 )
186 elif base <= 36:
187 cause = _(
188 "In base `base`, `int()` is most often use to convert a string\n"
189 "containing the digits `0` to `9` and the letters\n"
190 "from `'a'` to `'{max_n}'` into an integer.\n"
191 ).format(base=base, max_n=valid[base - 1])
192 else: # pragma: no cover
193 debug_helper.log(f"Invalid base argument caught by mistake {base}")
194 return {}
195
196 if base != 0:
197 cause += invalid
198
199 return {"cause": begin_cause + cause}
200
201
202 def _convert_to_float(value: Any) -> CauseInfo:
203 hint = _("You need to convert `'{value}'` to a float first.\n").format(value=value)
204 cause = _(
205 "The string `'{value}'` needs to be first converted using `float()`\n"
206 "before the result can be converted into an integer using `int()`.\n"
207 ).format(value=value)
208 return {"cause": cause, "suggest": hint}
209
210
211 @parser._add
212 def base_for_int(message: str, tb_data: TracebackData) -> CauseInfo:
213 if message != "int() base must be >= 2 and <= 36, or 0":
214 return {}
215 pattern = re.compile(r",\s*base\s*=(\d+)\s*\)")
216 cause = _(
217 "The argument `base` of `int()` must be either zero\n"
218 "or any integer from 2 to 36.\n"
219 )
220 match = re.search(pattern, tb_data.bad_line)
221 if match is None:
222 return {"cause": cause}
223 base_arg = match[1]
224 cause += _("You wrote {base} which is not allowed.\n").format(base=base_arg)
225 return {"cause": cause}
226
227
228 @parser._add
229 def date_month_must_be_between_1_and_12(
230 message: str, _tb_data: TracebackData
231 ) -> CauseInfo:
232 if message != "month must be in 1..12":
233 return {}
234
235 hint = _("Did you specify an invalid month?\n")
236 cause = _(
237 "I am guessing that you specify an invalid value for a month\n"
238 "in a `date` object. Valid values are integers, from 1 to 12.\n"
239 )
240 return {"cause": cause, "suggest": hint}
241
242
243 @parser._add
244 def could_not_convert_to_float(message: str, _tb_data: TracebackData) -> CauseInfo:
245 if not message.startswith("could not convert string to float: "):
246 return {}
247 pattern = re.compile(r"could not convert string to float: '(.*)'")
248 match = re.search(pattern, message)
249 if match is None:
250 debug_helper.log("Could not find match in could_not_convert_to_float.")
251 return {}
252 string = match[1]
253 cause = _(
254 "The string `{string}` cannot be converted to a `float`\n"
255 "as it does not represent a number.\n"
256 ).format(string=string)
257 return {"cause": cause}
258
259
260 @parser._add
261 def slots_conflicts_with_class_variable(
262 message: str, _tb_data: TracebackData
263 ) -> CauseInfo:
264 pattern = r"'(.*)' in __slots__ conflicts with class variable"
265 match = re.search(pattern, message)
266 if not match:
267 return {}
268 var = match[1]
269 cause = _(
270 "The name `{var}` is used both as the name of a class variable\n"
271 "and as a string item in the class `__slots__`;\n"
272 "this is not allowed.\n"
273 ).format(var=var)
274 return {"cause": cause}
275
276
277 @parser._add
278 def pow_third_arg_cannot_be_zero(message: str, _tb_data: TracebackData) -> CauseInfo:
279 if message != "pow() 3rd argument cannot be 0":
280 return {}
281 return {"cause": _("The third argument of the function `pow()` cannot be zero.\n")}
282
283
284 @parser._add
285 def unrecognized_message(_message: str, tb_data: TracebackData) -> CauseInfo:
286 """This attempts to provide some help when a message is not recognized."""
287 bad_line = tb_data.bad_line.strip()
288 frame = tb_data.exception_frame
289
290 if bad_line.startswith("raise ") or bad_line.startswith("raise\t"):
291 try:
292 name = inspect.getframeinfo(frame).function
293 fn_obj = frame.f_globals[name]
294 except Exception: # noqa
295 return {}
296 else:
297 all_objects = info_variables.get_all_objects(bad_line, frame)["name, obj"]
298 callables = []
299 for name, obj in all_objects:
300 if callable(obj):
301 callables.append((name, obj))
302 if not callables:
303 return {}
304
305 tokens = token_utils.get_significant_tokens(tb_data.bad_line)
306 name, fn_obj = callables[0]
307 if name != tokens[0]:
308 return {}
309
310 cause = _(
311 "I do not recognize this error message.\n"
312 "I am guessing that the problem is with the function `{name}`.\n"
313 ).format(name=name)
314
315 if hasattr(fn_obj, "__doc__") and fn_obj.__doc__ is not None:
316 cause += _("Its docstring is:\n\n{docstring}\n").format(
317 docstring="'''" + fn_obj.__doc__ + "'''"
318 )
319 else:
320 cause += _("I have no more information.\n")
321 return {"cause": cause}
322
323
324 @parser._add
325 def time_strftime_incorrect_format(message: str, _tb_data: TracebackData) -> CauseInfo:
326 pattern = r"time data '(.*)' does not match format '(.*)'"
327 match = re.search(pattern, message)
328 if not match:
329 return {}
330 cause = _(
331 "The value you gave for the time is not in the format you specified.\n"
332 "Make sure to use the same separator between items\n"
333 "(for example, between day and month) and keep the order the same\n"
334 "in both the data provided and the format you specified.\n"
335 "The following table might be useful:\n"
336 "https://docs.python.org/3/library/time.html#time.strftime\n"
337 "The following site might also be useful: https://www.strfti.me/\n"
338 )
339 return {"cause": cause}
340
341
342 @parser._add
343 def list_remove_x_not_in_list(message: str, tb_data: TracebackData) -> CauseInfo:
344 if message != "list.remove(x): x not in list":
345 return {}
346 bad_line = tb_data.bad_line
347 frame = tb_data.exception_frame
348 all_objects = info_variables.get_all_objects(bad_line, frame)["name, obj"]
349 dot_remove = 0
350 list_remove = the_list = ""
351 for name, obj in all_objects:
352 if "." in name and "remove" in name:
353 dot_remove += 1
354 list_remove = name
355 elif isinstance(obj, list):
356 the_list = name
357
358 if dot_remove == 1 and not the_list:
359 # for a literal [1, 2].remove(3)
360 the_list = list_remove.replace("remove", "").strip()[:-1]
361
362 if dot_remove == 1 and the_list:
363 item = bad_line.replace(list_remove, "").strip()[1:-1].strip()
364 the_list = list_remove.replace("remove", "").strip()[:-1]
365 cause = _(
366 "You have attempted to remove `{item}` from the list `{the_list}`.\n"
367 "However, `{the_list}` does not contain `{item}`.\n"
368 ).format(the_list=the_list, item=item)
369 elif the_list:
370 cause = _(
371 "You have attempted to remove an item from the list `{the_list}`.\n"
372 "However, `{the_list}` does not contain that item.\n"
373 ).format(the_list=the_list)
374 else:
375 cause = _(
376 "You have attempted to remove an item a list that does not contain such an item.\n"
377 )
378 return {"cause": cause} if cause else {}
379
380
381 @parser._add
382 def generic_explanation_already_exist(
383 message: str, _tb_data: TracebackData
384 ) -> CauseInfo:
385 # See info_generic.py
386 # TODO: add unit test
387 pattern = "A description of `(.*)` means already exists:"
388 match = re.search(pattern, message)
389 if not match:
390 return {}
391 cause = _(
392 "An explanation of `{exception}` already exists.\n"
393 "If you think that a better explanation can be given, please file an issue.\n"
394 ).format(exception=match[1])
395 return {"cause": cause}