Debian Codegraph @

friendly_traceback/runtime_errors/attribute_error.py

raw symbols SCIP
1 """Getting specific information for AttributeError"""
2
3 import ast
4 import builtins
5 import platform
6 import re
7 import sys
8 from types import FrameType
9 from typing import Any, Iterable, List, Optional, Sequence
10
11 from .. import console_helpers, debug_helper, info_variables, utils
12 from ..ft_gettext import current_lang, please_report
13 from ..message_parser import get_parser
14 from ..path_info import path_utils
15 from ..tb_data import TracebackData # for type checking only
16 from ..typing_info import CauseInfo # for type checking only
17 from ..utils import get_similar_words, list_to_string
18 from . import stdlib_modules
19
20 parser = get_parser(AttributeError)
21 _ = current_lang.translate
22
23
24 @parser._add
25 def circular_import(message: str, _tb_data: TracebackData) -> CauseInfo:
26 pattern = re.compile(r"partially initialized module '(.*)' has")
27 match = re.search(pattern, message)
28 if not match:
29 return {}
30 module = match[1]
31
32 if stdlib_modules.module_exists(module):
33 hint = _("Did you give your program the same name as a Python module?\n")
34 cause = _(
35 "I suspect that you used the name `{module}.py` for your program\n"
36 "and that you also wanted to import a module with the same name\n"
37 "from Python's standard library.\n"
38 "If so, you should use a different name for your program.\n"
39 ).format(module=module)
40 return {"cause": cause, "suggest": hint}
41
42 if "circular import" in message:
43 hint = _("You have a circular import.\n")
44 else: # pragma: no cover
45 # I thought a version did not include the mention of circular import.
46 debug_helper.log("New case to consider for circular_import.")
47 hint = _("You likely have a circular import.\n")
48 cause = _("Python indicated that the module `{module}` was not fully imported.\n")
49 cause += _(
50 "This can occur if, during the execution of the code in module `{module}`\n"
51 "an attempt is made to import the same module again.\n"
52 ).format(module=module)
53 return {"cause": cause, "suggest": hint}
54
55
56 # ======= Attribute error in module =========
57
58
59 @parser._add
60 def attribute_error_in_module(message: str, tb_data: TracebackData) -> CauseInfo:
61 """Attempts to find if a module attribute or module name might have been misspelled"""
62 pattern = re.compile(r"module '(.*)' has no attribute '(.*)'")
63 match = re.search(pattern, message)
64 if not match:
65 return {}
66 module = match[1]
67 attribute = match[2]
68 frame = tb_data.exception_frame
69
70 try:
71 mod = sys.modules[module]
72 except Exception: # noqa
73 cause = _(
74 "This should not happen:\n"
75 "Python tells us that module `{module}` does not have an "
76 "attribute named `{attribute}`.\n"
77 "However, it does not appear that module `{module}` was imported.\n"
78 ).format(module=module, attribute=attribute)
79 if stdlib_modules.module_exists(module):
80 hint = _("Did you give your program the same name as a Python module?\n")
81 cause += _(
82 "I suspect that you used the name `{module}.py` for your program\n"
83 "and that you also wanted to import a module with the same name\n"
84 "from Python's standard library.\n"
85 "If so, you should use a different name for your program.\n"
86 ).format(module=module)
87 return {"cause": cause, "suggest": hint}
88 else:
89 cause = hint = _("You likely have a circular import.\n")
90 cause += _(
91 "This can occur if, during the execution of the code in module `{module}`\n"
92 "an attempt is made to import the same module again.\n"
93 ).format(module=module)
94 return {"cause": cause, "suggest": hint}
95
96 similar_attributes = get_similar_words(attribute, dir(mod))
97 if similar_attributes:
98 if len(similar_attributes) == 1:
99 hint = _("Did you mean `{name}`?\n").format(name=similar_attributes[0])
100 cause = _(
101 "Perhaps you meant to write `{module}.{correct}` "
102 "instead of `{module}.{typo}`\n"
103 ).format(correct=similar_attributes[0], typo=attribute, module=module)
104 return {"cause": cause, "suggest": hint}
105
106 names = list_to_string(similar_attributes)
107 hint = _("Did you mean `{name}`?\n").format(name=similar_attributes[0])
108 cause = _(
109 "Instead of writing `{module}.{typo}`, perhaps you meant to write one of \n"
110 "the following names which are attributes of module `{module}`:\n"
111 "`{names}`\n"
112 ).format(names=names, typo=attribute, module=module)
113 return {"cause": cause, "suggest": hint}
114
115 if stdlib_modules.module_exists(module) and hasattr(mod, "__file__"):
116 mod_path = path_utils.shorten_path(mod.__file__)
117 if not mod_path.startswith("PYTHON_LIB:"):
118 hint = _("Did you give your program the same name as a Python module?\n")
119 cause = _(
120 "You imported a module named `{module}` from `{mod_path}`.\n"
121 "There is also a module named `{module}` in Python's standard library.\n"
122 "Perhaps you need to rename your module.\n"
123 ).format(module=module, mod_path=mod_path)
124 return {"cause": cause, "suggest": hint}
125
126 imported_modules = []
127 for mod_name in sys.modules:
128 if mod_name in frame.f_locals:
129 imported_modules.append((mod_name, frame.f_locals[mod_name]))
130 elif mod_name in frame.f_globals:
131 imported_modules.append((mod_name, frame.f_globals[mod_name]))
132
133 possible_modules = [
134 mod_name for mod_name, mod in imported_modules if attribute in dir(mod)
135 ]
136
137 if possible_modules:
138 if len(possible_modules) == 1:
139 mod_name = possible_modules[0]
140 hint = _("Did you mean `{name}`?\n").format(name=mod_name)
141 cause = _(
142 "Perhaps you meant to use the attribute `{attribute}` of \n"
143 "module `{mod_name}` instead of module `{module}`.\n"
144 ).format(attribute=attribute, mod_name=mod_name, module=module)
145 return {"cause": cause, "suggest": hint}
146
147 hint = _("Did you mean one of the following modules: `{names}`?").format(
148 names=list_to_string(possible_modules)
149 )
150 cause = _(
151 "Instead of the module `{module}`, perhaps you wanted to use\n"
152 "the attribute `{attribute}` of one of the following modules:\n"
153 "`{names}`.\n"
154 ).format(
155 attribute=attribute, module=module, names=list_to_string(possible_modules)
156 )
157 return {"cause": cause, "suggest": hint}
158
159 cause = _(
160 "Python tells us that no object with name `{attribute}` is\n"
161 "found in module `{module}`.\n"
162 ).format(attribute=attribute, module=module)
163 return {"cause": cause}
164
165
166 @parser._add
167 def type_object_has_no_attribute(message: str, tb_data: TracebackData) -> CauseInfo:
168 """Attempts to find if a module attribute or module name might have been misspelled"""
169 pattern = re.compile(r"type object '(.*)' has no attribute '(.*)'")
170 match = re.search(pattern, message)
171 if not match:
172 return {}
173 frame = tb_data.exception_frame
174 return _attribute_error_in_object(match[1], match[2], tb_data, frame)
175
176
177 def _invalid_add_note(exc_name, frame):
178 exc = info_variables.get_object_from_name(exc_name, frame)
179 if issubclass(exc, BaseException):
180 hint = _("`add_note()` is only allowed for Python version 3.11 and newer.\n")
181 using = _("You are using Python version {version}.\n").format(
182 version=platform.python_version()
183 )
184 return {"cause": hint + using, "suggest": hint}
185 return {}
186
187
188 @parser._add
189 def attribute_error_in_object(message: str, tb_data: TracebackData) -> CauseInfo:
190 pattern = re.compile(r"'(.*)' object has no attribute '(.*)'")
191 match = re.search(pattern, message)
192 if not match:
193 return {}
194 frame = tb_data.exception_frame
195
196 if match[1] == "NoneType":
197 return {
198 "cause": _(
199 "You are attempting to access the attribute `{attr}`\n"
200 "for a variable whose value is `None`."
201 ).format(attr=match[2])
202 }
203 if match[2] == "add_note" and sys.version_info < (3, 11):
204 cause = _invalid_add_note(match[1], frame)
205 if cause:
206 return cause
207
208 return _attribute_error_in_object(match[1], match[2], tb_data, frame)
209
210
211 @parser._add
212 def object_attribute_is_read_only(message: str, tb_data: TracebackData) -> CauseInfo:
213 pattern = r"'(.*)' object attribute '(.*)' is read-only"
214 match = re.search(pattern, message)
215 if match is None:
216 return {}
217 obj_type = match[1]
218 attribute = match[2]
219 frame = tb_data.exception_frame
220
221 obj = info_variables.get_object_from_name(obj_type, frame)
222 if not hasattr(obj, "__slots__"):
223 cause = _(
224 "The value of attribute `{attribute}` of objects of type `{obj_type}`\n"
225 "cannot be changed.\n"
226 "I have no further information.\n"
227 ).format(attribute=attribute, obj_type=obj_type)
228 return {"cause": cause}
229
230 slots = getattr(obj, "__slots__")
231 all_objects = info_variables.get_all_objects(tb_data.bad_line, frame)["name, obj"]
232 for obj_name, instance in all_objects:
233 try:
234 if isinstance(instance, obj) or instance == obj:
235 break
236 except Exception: # noqa
237 continue
238 else:
239 obj_name = obj_type
240
241 if len(slots) == 0:
242 cause = _(
243 "Object `{name}` uses an empty `__slots__` to prevent the modification\n"
244 "of any of its attributes.\n"
245 ).format(name=obj_name, attribute=attribute)
246 return {"cause": cause}
247
248 cause = _(
249 "Object `{name}` uses `__slots__` to specify which attributes can\n"
250 "be changed. The value of attribute `{name}.{attribute}` cannot be changed.\n"
251 ).format(name=obj_name, attribute=attribute)
252 if len(slots) == 1:
253 cause += (
254 "The only attribute of `{name}` whose value can be changed is"
255 "`{attribute}`.\n"
256 ).format(name=obj_name, attribute=slots[0])
257 elif len(slots) < 10:
258 cause += (
259 "The only attributes of `{name}` whose value can be changed are:\n"
260 "`{attributes}`.\n"
261 ).format(name=obj_name, attributes=utils.list_to_string(slots))
262 return {"cause": cause}
263
264
265 def _attribute_error_in_object(
266 obj_type: str, attribute: str, tb_data: TracebackData, frame: FrameType
267 ) -> CauseInfo:
268 """Attempts to find if object attribute might have been misspelled"""
269 if obj_type == "builtin_function_or_method":
270 obj_name = tb_data.bad_line.replace("." + attribute, "")
271 # Confirm we have the right one
272 if obj_name in dir(builtins):
273 cause = _(
274 "`{obj_name}` is a function. Perhaps you meant to write\n"
275 "`{obj_name}({attribute})`\n"
276 ).format(obj_name=obj_name, attribute=attribute)
277 hint = _("Did you mean `{obj_name}({attribute})`?\n").format(
278 obj_name=obj_name, attribute=attribute
279 )
280 return {"cause": cause, "suggest": hint}
281
282 cause = _(
283 "`{obj_name}` is a Python built-in function or method\n"
284 "which does not have an attribute named `{attribute}.`\n"
285 ).format(obj_name=obj_name, attribute=attribute)
286 return {"cause": cause}
287
288 all_objects = info_variables.get_all_objects(tb_data.bad_line, frame)["name, obj"]
289 obj = info_variables.get_object_from_name(obj_type, frame)
290
291 if obj is None: # object could be an instance of obj_type
292 # this is to fix issue #212
293 for obj_name, _obj in all_objects:
294 t = str(type(_obj))
295 if (
296 t.endswith(f".{obj_type}'>") or t.endswith(f"'{obj_type}'>")
297 ) and not hasattr(_obj, attribute):
298 instance = _obj
299 break
300 else:
301 cause = _(
302 "An object of type `{obj_type}` has no attribute named `{attr}`.\n"
303 "Unfortunately I cannot find such an object on the line where\n"
304 "the problem occurs.\n"
305 ).format(obj_type=obj_type, attr=attribute)
306 return {"cause": cause + please_report()}
307 else:
308 for obj_name, instance in all_objects:
309 try:
310 if isinstance(instance, obj) or instance == obj:
311 break
312 except TypeError:
313 pass
314 else:
315 possible_objects = []
316 for obj_name, _obj in all_objects:
317 t = str(type(_obj))
318 if (
319 (t.endswith(f".{obj_type}'>") or t.endswith(f"'{obj_type}'>"))
320 and not hasattr(_obj, attribute)
321 ) or (
322 obj_name == "Friendly"
323 and isinstance(_obj, console_helpers.FriendlyHelpers)
324 ):
325 possible_objects.append((obj_name, _obj))
326
327 if not possible_objects:
328 debug_helper.log(f"bad_line= {tb_data.bad_line}")
329 cause = _(
330 "An object of type `{obj_type}` has no attribute named `{attr}`.\n\n"
331 "I cannot give additional information:\n"
332 "I found one object of this type in the current scope\n"
333 "but it does not appear to be the object causing the problem.\n"
334 ).format(obj_type=obj_type, attr=attribute)
335 return {"cause": cause + please_report()}
336 elif len(possible_objects) > 1:
337 names = ", ".join(name for name, _obj in possible_objects)
338 cause = _(
339 "An object of type `{obj_type}` has no attribute named `{attr}`.\n\n"
340 "The following objects might be the cause of the problem: \n"
341 "{names}.\n"
342 ).format(obj_type=obj_type, attr=attribute, names=names)
343 return {"cause": cause}
344
345 obj_name, instance = possible_objects[0]
346
347 possible_cause = tuple_by_accident(instance, obj_name, attribute)
348 if possible_cause:
349 return possible_cause
350
351 known_attributes = dir(instance)
352
353 # Example: this.len -> len(this)
354 known_builtin = perhaps_builtin(attribute, known_attributes)
355 if known_builtin:
356 return use_builtin_function(obj_name, attribute, known_builtin)
357
358 if attribute == "join":
359 join = perhaps_join(obj)
360 if join:
361 return use_str_join(obj_name, tb_data)
362
363 # Example: both "this" and "that" are known objects
364 # this.that -> this, that
365 if attribute in frame.f_globals or attribute in frame.f_locals:
366 return missing_comma(obj_name, attribute)
367
368 known_synonyms = perhaps_synonym(attribute, known_attributes)
369 if known_synonyms:
370 return use_synonym(obj_name, attribute, known_synonyms)
371
372 # noqa Example: list.apend -> list.append
373 similar = get_similar_words(attribute, known_attributes)
374 if similar:
375 return handle_attribute_typo(obj_name, attribute, similar)
376
377 # We have not been able to find a useful suggestion
378 cause = _("The object `{obj}` has no attribute named `{attr}`.\n").format(
379 obj=obj_name, attr=attribute
380 )
381 if hasattr(obj, "__slots__"):
382 cause += _(
383 "Note that object `{obj}` uses `__slots__` which prevents\n"
384 "the creation of new attributes.\n"
385 ).format(obj=obj_name)
386 known_attributes = [a for a in known_attributes if "__" not in a]
387 if len(known_attributes) > 10:
388 known_attributes = known_attributes[:9] + ["..."]
389 if known_attributes:
390 cause += _(
391 "The following are some of its known attributes:\n`{names}`."
392 ).format(names=", ".join(known_attributes))
393 return {"cause": cause}
394
395
396 def handle_attribute_typo(
397 obj_name: str, attribute: str, similar: Sequence[str]
398 ) -> CauseInfo:
399 """Takes care of misspelling of existing attribute of object whose
400 name could be identified.
401 """
402 cause = _("The object `{obj_name}` has no attribute named `{attribute}`.\n").format(
403 obj_name=obj_name, attribute=attribute
404 )
405 if len(similar) == 1:
406 hint = _("Did you mean `{name}`?\n").format(name=similar[0])
407 cause += _(
408 "Perhaps you meant to write `{obj}.{correct}` "
409 "instead of `{obj}.{typo}`\n"
410 ).format(correct=similar[0], typo=attribute, obj=obj_name)
411 else:
412 names = list_to_string(similar)
413 hint = _("Did you mean one of the following: `{names}`?\n").format(names=names)
414 cause += _(
415 "Instead of writing `{obj}.{typo}`, perhaps you meant to write one of \n"
416 "the following names which are attributes of object `{obj}`:\n"
417 "`{names}`\n"
418 ).format(names=names, typo=attribute, obj=obj_name)
419 return {"cause": cause, "suggest": hint}
420
421
422 def perhaps_builtin(attribute: str, known_attributes: Iterable[str]) -> Optional[str]:
423 if attribute in {"min", "max", "sorted", "reversed", "sum"}:
424 return attribute
425 elif (
426 attribute in {"len", "length", "lenght", "size"} # noqa
427 and "__len__" in known_attributes
428 ):
429 return "len"
430 return None
431
432
433 def tuple_by_accident(obj: Any, obj_name: str, attribute: str) -> CauseInfo:
434 if not (isinstance(obj, tuple) and len(obj) == 1):
435 return {}
436
437 true_obj = obj[0]
438 if hasattr(true_obj, attribute):
439 hint = _("Did you write a comma by mistake?\n")
440 cause = _(
441 "`{obj_name}` is a tuple that contains a single item\n"
442 "which does have `'{attribute}'` as an attribute.\n"
443 "Perhaps you added a trailing comma by mistake at the end of the line\n"
444 "where you defined `{obj_name}`.\n"
445 ).format(obj_name=obj_name, attribute=attribute)
446 return {"cause": cause, "suggest": hint}
447
448 return {}
449
450
451 def use_str_join(obj_name: str, tb_data: TracebackData) -> CauseInfo:
452 str_content = repr("...")
453 hint = _("Did you mean `{str_content}.join({obj_name})`?\n")
454 cause = _(
455 "The object `{obj_name}` has no attribute named `join`.\n"
456 "Perhaps you wanted something like `{str_content}.join({obj_name})`.\n"
457 )
458 parts = tb_data.original_bad_line.split(tb_data.bad_line)
459 if len(parts) >= 2 and parts[1].strip().startswith("("):
460 index = parts[1].find(")")
461 if index != -1:
462 content = parts[1][1:index].strip()
463 try:
464 content = ast.literal_eval(content)
465 except Exception: # noqa
466 content = None # type: ignore
467 if isinstance(content, str):
468 str_content = repr(content)
469 hint = hint.format(obj_name=obj_name, str_content=str_content)
470 cause = cause.format(obj_name=obj_name, str_content=str_content)
471 return {"cause": cause, "suggest": hint}
472
473
474 def use_builtin_function(
475 obj_name: str, attribute: str, known_builtin: str
476 ) -> CauseInfo:
477 hint = _("Did you mean `{known_builtin}({obj_name})`?\n").format(
478 known_builtin=known_builtin, obj_name=obj_name
479 )
480 cause = _(
481 "The object `{obj_name}` has no attribute named `{attribute}`.\n"
482 "Perhaps you can use the Python builtin function `{known_builtin}` instead:\n"
483 "`{known_builtin}({obj_name})`."
484 ).format(known_builtin=known_builtin, obj_name=obj_name, attribute=attribute)
485 return {"cause": cause, "suggest": hint}
486
487
488 def perhaps_join(obj: Any) -> bool:
489 return bool(
490 hasattr(obj, "__iter__")
491 or (hasattr(obj, "__getitem__") and hasattr(obj, "__len__"))
492 )
493
494
495 def perhaps_synonym(
496 attribute: str, known_attributes: Iterable[str]
497 ) -> Optional[List[str]]:
498 synonyms = [
499 ["add", "append", "extend", "insert", "push", "update", "union"],
500 ["remove", "discard", "pop"],
501 ]
502 for syn_list in synonyms:
503 if attribute in syn_list:
504 return [attr for attr in syn_list if attr in known_attributes]
505 return None
506
507
508 def use_synonym(obj_name: str, attribute: str, synonyms: Sequence[str]) -> CauseInfo:
509 hint = _("Did you mean `{attr}`?\n").format(attr=synonyms[0])
510 cause = _("The object `{name}` has no attribute named `{attribute}`.\n").format(
511 name=obj_name, attribute=attribute
512 )
513 if len(synonyms) == 1:
514 cause += _(
515 "However, `{attr}` is an attribute of `{name}` with a similar meaning.\n"
516 ).format(name=obj_name, attr=synonyms[0])
517 else:
518 cause += _(
519 "However, `{name}` has the following attributes with similar meanings:\n"
520 "`{attributes}`.\n"
521 ).format(name=obj_name, attributes=list_to_string(synonyms))
522
523 return {"cause": cause, "suggest": hint}
524
525
526 def missing_comma(first: str, second: str) -> CauseInfo:
527 hint = _("Did you mean to separate object names by a comma?\n")
528
529 cause = _(
530 "`{second}` is not an attribute of `{first}`.\n"
531 "However, both `{first}` and `{second}` are known objects.\n"
532 "Perhaps you wrote a period to separate these two objects, \n"
533 "instead of using a comma.\n"
534 ).format(first=first, second=second)
535
536 return {"cause": cause, "suggest": hint}