Debian Codegraph @

friendly_traceback/info_variables.py

raw symbols SCIP
1 # sourcery skip: use-contextlib-suppress
2 """info_variables.py
3
4 Used to provide basic variable information in a way that
5 can be useful for beginners without overwhelming them.
6 """
7 import ast
8 import builtins
9 import re
10 import sys
11 import types
12 from typing import Any, Dict, List, Tuple, Union
13
14 from . import debug_helper, token_utils, utils
15 from .ft_gettext import current_lang
16 from .path_info import path_utils
17 from .typing_info import ObjectsInfo, ScopeKind, SimilarNamesInfo
18
19 # third-party
20 try:
21 from asttokens import ASTTokens # noqa
22 from pure_eval import Evaluator, group_expressions # noqa
23 except ImportError: # pragma: no cover
24 pass # ignore errors when processed by Sphinx
25
26
27 INDENT = " " * 8
28 MAX_LENGTH = 65
29 _ = current_lang.translate
30 RENAMED_BUILTINS = set()
31
32
33 class ConfidentialInformation:
34 """Used to hide values of confidential information"""
35
36 regex = []
37 redacted = "'••••••'"
38
39 def hide_confidential_information(self, patterns: Union[List, None] = None) -> None:
40 """Use to record words or regular expression patterns that determine
41 if a variable represents confidential information.
42 """
43 if patterns is not None:
44 for pattern in patterns:
45 self.regex.append(re.compile(pattern))
46
47 def is_confidential(self, name: str) -> bool:
48 """Identify variable names that are deemed to contain confidential information"""
49 return any(re.fullmatch(pattern, name) for pattern in self.regex)
50
51 def redact_confidential(self, name: str, value: Any) -> Any:
52 if confidential.is_confidential(name):
53 return confidential.redacted
54 # The value passed is the repr of the object.
55 # We could have a dict whose key is a confidential name, and which
56 # would be shown, with its corresponding item. To guard against such
57 # cases, we redact any value that contains confidential names or patters.
58 for pattern in self.regex:
59 if re.findall(pattern, value):
60 return confidential.redacted
61 return value
62
63
64 confidential = ConfidentialInformation()
65
66
67 def convert_type(short_form: str) -> str:
68 forms = {
69 "complex": _("a complex number"),
70 "dict": _("a dictionary (`dict`)"),
71 "float": _("a number (`float`)"),
72 "frozenset": _("a `frozenset`"),
73 "int": _("an integer (`int`)"),
74 "list": _("a `list`"),
75 "NoneType": _("a variable equal to `None` (`NoneType`)"),
76 "set": _("a `set`"),
77 "str": _("a string (`str`)"),
78 "string": _("a string (`str`)"),
79 "tuple": _("a `tuple`"),
80 }
81 return forms.get(short_form, f"`{short_form}`")
82
83
84 def get_all_objects(line: str, frame: types.FrameType) -> ObjectsInfo:
85 # sourcery skip: assign-if-exp, simplify-generator
86 """Given a (partial) line of code and a frame,
87 obtains a dict containing all the relevant information about objects
88 found on that line so that they can be formatted as part of the
89 answer to "where()" or they can be used during the analysis
90 of the cause of the exception.
91
92 The dict returned has six keys.
93 The first three, 'locals', 'globals', 'builtins',
94 each containing a list of tuples, each tuple being of the form
95 (name, repr(obj), obj) where name --> obj.
96
97 The fourth key, 'expressions', contains a list of tuples of the form
98 ('name', obj). It is only occasionally used in helping to make
99 suggestions regarding the cause of some exception.
100 """
101 objects: ObjectsInfo = {
102 "locals": [],
103 "globals": [],
104 "builtins": [],
105 "expressions": [],
106 "name, obj": [],
107 "name, type": [],
108 }
109 names = set()
110 objects, names = find_identifiers(objects, line, frame, names)
111 return find_expressions(objects, line, frame, names)
112
113
114 def find_identifiers(
115 objects: ObjectsInfo, line: str, frame: types.FrameType, names: set
116 ) -> Tuple[ObjectsInfo, set]:
117 """finds all the identifiers and corresponding objects"""
118 scopes = (
119 ("locals", frame.f_locals), # always have locals before globals
120 ("globals", frame.f_globals),
121 )
122 tokens = token_utils.get_significant_tokens(line)
123 if not tokens:
124 return objects, names
125 for tok in tokens:
126 if tok.is_identifier():
127 name = tok.string
128 if name in names:
129 continue
130 for scope, scope_dict in scopes:
131 if name in scope_dict:
132 names.add(name)
133 obj = scope_dict[name]
134 objects[scope].append((name, obj))
135 objects["name, obj"].append((name, obj))
136 obj_type = type(obj).__name__
137 if obj_type is not None:
138 objects["name, type"].append((name, obj_type))
139 break
140 else:
141 if name in dir(builtins):
142 names.add(name)
143 obj = getattr(builtins, name)
144 objects["builtins"].append((name, obj))
145 objects["name, obj"].append((name, obj))
146 obj_type = type(obj).__name__
147 if obj_type is not None:
148 objects["name, type"].append((name, obj_type))
149 return objects, names
150
151
152 def find_expressions(
153 objects: ObjectsInfo, line: str, frame: types.FrameType, names: set
154 ) -> ObjectsInfo: # sourcery skip: simplify-generator, use-contextlib-suppress
155 """Use asttokens to find expressions of interest to include in variables shown."""
156 line = line.strip()
157 if line.startswith(
158 ("def ", "if ", "while ", "class ", "for ", "with ")
159 ) and line.endswith(":"):
160 line += " pass"
161
162 try:
163 atok = ASTTokens(line.strip(), parse=True)
164 except SyntaxError as e:
165 if "unexpected EOF" in str(e):
166 return objects
167 if "\n" in line:
168 newline = " ".join(line.split())
169 try:
170 atok = ASTTokens(newline.strip(), parse=True)
171 except SyntaxError as e:
172 debug_helper.log(f"Problem with ASTTokens: {e}" + f"\nline: {line}")
173 return objects
174 else:
175 debug_helper.log(f"Problem with ASTTokens: {e}" + f"\nline: {line}")
176 return objects
177
178 if atok is not None:
179 evaluator = Evaluator.from_frame(frame)
180 try:
181 for nodes, obj in group_expressions(
182 pair for pair in evaluator.find_expressions(atok.tree)
183 ):
184 name = atok.get_text(nodes[0])
185 if not name or name in names:
186 continue
187 names.add(name)
188 objects["name, obj"].append((name, obj))
189 try:
190 # We're not interested in showing literals in the list of variables
191 ast.literal_eval(name)
192 except Exception: # noqa
193 objects["expressions"].append((name, obj))
194 except Exception: # noqa
195 # The example in https://github.com/ipython/ipython/issues/13481
196 # give rises to a TypeError exception here.
197 pass
198
199 return objects
200
201
202 def get_object_from_name(name: str, frame: types.FrameType) -> Any:
203 """Given the name of an object, for example 'str', or 'A' for
204 class A, returns a basic object of that type found in a frame,
205 or None.
206 """
207 # TODO:
208 """
209 There might be multiple objects with the same name (in different scope)
210 in a given frame. For example:
211
212 class A: pass # first A
213 def f():
214 class A: pass # second A
215 return A()
216 a = f()
217 a.x # raise AttributeError: 'A' object has no attribute 'x'
218
219 Here, we would identify 'A' as being the first, even though 'a' is an
220 instance of the second 'A'.
221
222 This should be tested thoroughly and likely result in a warning given
223 about possibly not being able to identify the correct object.
224 """
225 # We must guard against people defining their own type with a
226 # standard name by checking standard types last.
227
228 # We will limit to only one dot i.e. 'name.attribute'
229 if "." in name:
230 if name.count(".") > 1:
231 print(name.count("."), name)
232 return None
233 name, attribute = name.replace(" ", "").split(".")
234 else:
235 attribute = None
236
237 if name in frame.f_locals:
238 if attribute is None:
239 return frame.f_locals[name]
240 obj = frame.f_locals[name]
241 if hasattr(obj, attribute):
242 return getattr(obj, attribute)
243
244 if name in frame.f_globals:
245 if attribute is None:
246 return frame.f_globals[name]
247 obj = frame.f_globals[name]
248 if hasattr(obj, attribute):
249 return getattr(obj, attribute)
250
251 return getattr(builtins, name) if name in dir(builtins) else None
252
253
254 def get_variables_in_frame_by_scope(
255 frame: types.FrameType, scope: ScopeKind
256 ) -> Dict[str, Any]:
257 """Returns a list of variables based on the provided scope, which must
258 be one of 'local', 'global', or 'nonlocal'.
259 """
260 if scope == "local":
261 return frame.f_locals
262
263 if scope == "global":
264 return frame.f_globals
265
266 if scope == "nonlocal":
267 non_locals = {}
268 while frame.f_back is not None:
269 frame = frame.f_back
270 # By creating a new list here, we prevent a failure when
271 # running with pytest.
272 for key in list(frame.f_locals):
273 if key in non_locals:
274 continue
275 non_locals[key] = frame.f_locals[key]
276 return non_locals
277
278
279 def get_definition_scope(variable_name: str, frame: types.FrameType) -> List[ScopeKind]:
280 """Returns a list of scopes ('local', 'global', 'nonlocal')
281 in which a variable is defined.
282 """
283 scopes = []
284 nonlocal_vars = get_variables_in_frame_by_scope(frame, "nonlocal")
285 if variable_name in frame.f_locals:
286 scopes.append("local")
287 if variable_name in frame.f_globals:
288 scopes.append("global")
289 if variable_name in nonlocal_vars and (
290 variable_name not in frame.f_globals
291 or nonlocal_vars[variable_name] != frame.f_globals[variable_name]
292 ):
293 scopes.append("nonlocal")
294 return scopes
295
296
297 def get_var_info(line: str, frame: types.FrameType) -> dict:
298 """Given a frame object, it obtains the value (repr) of the names
299 found in the logical line (which may span many lines in the file)
300 where the exception occurred.
301
302 We ignore values found *only* in nonlocal scope as they should not
303 be relevant.
304 """
305
306 names_info = []
307 objects = get_all_objects(line.strip(), frame)
308
309 objects["locals"].sort()
310 for name, obj in objects["locals"]:
311 result = format_var_info(name, obj)
312 names_info.append(result)
313
314 objects["globals"].sort()
315 for name, obj in objects["globals"]:
316 result = format_var_info(name, obj, "globals")
317 names_info.append(result)
318
319 objects["builtins"].sort()
320 for name, obj in objects["builtins"]:
321 result = format_var_info(name, obj)
322 names_info.append(result)
323
324 objects["expressions"].sort()
325 for name, obj in objects["expressions"]:
326 result = format_var_info(name, obj)
327 names_info.append(result)
328
329 if names_info:
330 names_info.append("")
331 var_info = {"var_info": "\n".join(names_info)}
332 builtins_warnings = find_renamed_builtins(frame)
333 if builtins_warnings:
334 var_info["additional_variable_warning"] = builtins_warnings
335 return var_info
336
337
338 def find_renamed_builtins(frame) -> str:
339 warnings = ""
340 for name in dir(builtins):
341 if name.startswith("_"):
342 continue
343 if (
344 name == "pow"
345 and "cos" in frame.f_locals
346 and "cosh" in frame.f_locals
347 and "pi" in frame.f_locals
348 ):
349 # we likely did 'from math import *' which redefines pow;
350 # no warning needed in this case
351 continue
352 if name in frame.f_locals:
353 builtin_obj = getattr(builtins, name)
354 obj = frame.f_locals[name]
355 if builtin_obj != obj:
356 if name not in RENAMED_BUILTINS: # only once
357 warnings += _(
358 "Friendly warning: you have redefined the python builtin `{name}`.\n"
359 ).format(name=name)
360 RENAMED_BUILTINS.add(name)
361 elif name in RENAMED_BUILTINS:
362 RENAMED_BUILTINS.remove(name)
363 elif name in RENAMED_BUILTINS:
364 RENAMED_BUILTINS.remove(name)
365
366 return warnings
367
368
369 def simplify_repr(value: str, splitlines: bool = True) -> str:
370 """Remove irrelevant memory location information from functions, etc.
371
372 Does additional formatting in an attempt to make the values (repr)
373 more readable.
374 """
375 if not value.startswith("<") or not value.endswith(">"):
376 debug_helper.log("simplify_repr called on value that is not of the form <...>")
377 debug_helper.log(f"value={value}")
378 return value
379 end_angle = ">>" if value.endswith(">>") else ">"
380
381 bound_method = "bound method" in value
382 if " at " in value:
383 # There are two reasons to remove the memory location information:
384 # 1. this information is essentially of no value for beginners
385 # 2. Removing this information ensures that consecutive runs of
386 # script to create tracebacks for the documentation will yield
387 # exactly the same results.
388 # This makes it easier to spot changes/regressions.
389 value = value.split(" at ")[0] + end_angle
390 elif " from " in value: # example: module X from stdlib_path
391 obj_repr, path = value.split(" from ")
392 path = path_utils.shorten_path(path[:-1]) # -1 removes >
393 # Avoid lines that are too long
394 if len(obj_repr) + len(path) > MAX_LENGTH and splitlines:
395 value = f"{obj_repr}>\n{INDENT}from {path}"
396 else:
397 value = f"{obj_repr}> from {path}"
398
399 # Replace some strings so that colour formatting is nicer
400 value = value.replace("<class '", "<class ")
401 value = value.replace("<module '", "<module ")
402 value = value.replace("'>", ">")
403 value = value.replace("' (built-in)", " (built-in)")
404 # The following replacement is done so that, when using rich, pygments
405 # does not style the - and 'in' in a weird way.
406 value = value.replace("built-in", "builtin")
407 if bound_method:
408 value = simplify_bound_method(value, splitlines=splitlines)
409 elif ".<locals>." in value:
410 parts = value.split(".<locals>.")
411 file_name = ".<locals>".join(parts[:-1])
412 obj_name = parts[-1]
413 if value.startswith("<function "):
414 start = "<function "
415 elif value.startswith("<class "):
416 start = "<class "
417 else:
418 start = "<"
419 file_name = file_name.replace(start, "").replace(".locals>", ".<locals>.")
420 value = start + obj_name + " defined in <function " + file_name + ">"
421 if len(value) > MAX_LENGTH and splitlines:
422 value = (
423 start + obj_name + f"\n{INDENT}defined in <function " + file_name + ">"
424 )
425
426 if "__main__." in value: # pragma: no cover
427 value = value.replace("__main__.", "")
428 return value
429
430
431 def simplify_bound_method(name: str, splitlines: bool = False) -> str:
432 name = name[:-1] # remove final >
433 if ".<locals>." in name:
434 method, obj = name.split(" of ")
435 parts = method.split(".<locals>.")
436 method = f"<bound method {parts[-1]}>"
437 obj_parts = obj.split(".<locals>.")
438 file_name = ".<locals>".join(obj_parts[:-1])
439 obj_name = obj_parts[-1]
440 name = f"{method} of <{obj_name}` defined in `<function {file_name[1:]}>"
441 if len(name) > MAX_LENGTH and splitlines:
442 of_object = f"\n{INDENT}of <{obj_name}"
443 defined_in = f"\n{INDENT}defined in <function {file_name[1:]}>"
444 name = method + of_object + defined_in
445 else:
446 name = name.replace(" of", "> of")
447 return name
448
449
450 def safe_repr(obj: Any) -> str:
451 try: # guard against the case where obj == Friendly; #106
452 obj_repr = str(obj.true_repr())
453 # wrapped in str() for added security in case someone
454 # else uses an attribute called true_repr
455 except Exception: # skipcq: PYL-W0703 - see PR #201 ... # noqa
456 # ... we ignore any attribute access failures here, not only AttributeError
457 try:
458 obj_repr = repr(obj)
459 except Exception: # issue #161: repr not returning a string # noqa
460 obj_repr = str(type(obj))
461 return obj_repr
462
463
464 def format_var_info(name: str, obj: str, _global: str = "") -> str:
465 """Formats the variable information so that it fits on a single line
466 for each variable.
467
468 The format we want is something like the following:
469
470 [global] name: repr(name)
471
472 However, if repr(name) exceeds a certain value, it is truncated.
473 When that is the case, if len(name) is defined, as is the case for
474 lists, tuples, dicts, etc., then len(name) is shown on a separate line.
475 This can be useful information in case of IndexError and possibly
476 others.
477 """
478 length_info = ""
479 if _global:
480 _global = "global "
481
482 obj_repr = safe_repr(obj)
483 obj_repr = confidential.redact_confidential(name, obj_repr)
484
485 if obj_repr.startswith("<") and obj_repr.endswith(">"):
486 obj_repr = simplify_repr(obj_repr)
487 elif "\n" in obj_repr:
488 obj_repr = format_multiline(obj_repr)
489 elif len(obj_repr) > MAX_LENGTH:
490 obj_repr, length_info = shorten_long_line(obj_repr, obj)
491
492 result = f" {_global}{name}: {obj_repr}"
493 if length_info:
494 indent = " " * min(7 + len(name), 12)
495 result += f"\n{indent}len({name}): {length_info}\n"
496 return result
497
498
499 def format_multiline(value: str) -> str:
500 # This is useful for tabular data
501 indent = "\n" + " " * 8
502 lines = value.split("\n")
503 new_lines = [line if len(line) < 72 else f"{line[:68]}..." for line in lines]
504 if len(new_lines) > 6:
505 new_lines = new_lines[:6] + ["..."]
506 return indent + indent.join(new_lines)
507
508
509 def shorten_long_line(value: str, obj: str) -> (str, str):
510 # We reduce the length of the repr, indicate this by ..., but we
511 # also keep the last character so that the repr of a list still
512 # ends with ], that of a tuple still ends with ), etc.
513 if "," in value: # try to truncate at a natural place
514 parts = value.split(", ")
515 length = 0
516 new_parts = []
517 for part in parts:
518 if len(part) + length > MAX_LENGTH:
519 break
520 new_parts.append(f"{part}, ")
521 length += len(part) + 2
522 if new_parts:
523 value = "".join(new_parts) + "..." + value[-1]
524 else:
525 value = f"{value[:MAX_LENGTH - 5]}...{value[-1]}"
526 else:
527 value = f"{value[:MAX_LENGTH - 5]}...{value[-1]}"
528 try:
529 length_info = len(obj)
530 except OverflowError:
531 length_info = _("Object too large to be processed by Python.")
532 except TypeError:
533 length_info = ""
534 except Exception as e:
535 length_info = _("Unable to compute.") + f" ({e.__class__.__name__})"
536 return value, length_info
537
538
539 def get_similar_names(
540 name: str, frame: types.FrameType, include_builtins: bool = True
541 ) -> SimilarNamesInfo:
542 """This function looks for objects with names similar to 'name' in
543 either the current locals() and globals() as well as in
544 Python's builtins.
545 """
546 similar: SimilarNamesInfo = {}
547 # We need to first combine the candidates from all possible sources
548 # to treat them on an equal footing.
549 locals_ = list(frame.f_locals.keys())
550 globals_ = list(frame.f_globals.keys())
551 builtins_ = dir(builtins) if include_builtins else []
552 all_similar = utils.get_similar_words(name, locals_ + globals_ + builtins_)
553 similar["locals"] = []
554 similar["globals"] = []
555 similar["builtins"] = []
556 similar["best"] = ""
557 for word in all_similar:
558 if word in locals_:
559 similar["locals"].append(word)
560 elif word in globals_:
561 similar["globals"].append(word)
562 else:
563 similar["builtins"].append(word)
564 if all_similar:
565 most_similar = utils.get_similar_words(name, all_similar)
566 similar["best"] = most_similar[0]
567 elif name in {"length", "lenght"}:
568 # utils.get_similar_words() used above only look for relatively
569 # minor letter mismatches in making suggestions.
570 # Here we add a few additional hard-coded cases.
571 similar["builtins"] = ["len"]
572 similar["best"] = "len"
573 return similar
574
575
576 def name_has_type_hint(name: str, frame: types.FrameType) -> str:
577 """Identifies if a variable name has a type hint associated with it.
578
579 This can be useful if a user write something like::
580
581 name : something
582 use(name)
583
584 instead of::
585
586 name = something
587 use(name)
588
589 and sees a NameError.
590
591 HOWEVER, when an exception is raised, it seems that the only type hints
592 that are picked up correctly are those found in the global scope.
593 """
594 type_hint_found_in_scope = _(
595 "A type hint found for `{name}` in the {scope} scope.\n"
596 "Perhaps you had used a colon instead of an equal sign and wrote\n\n"
597 " {name} : {hint}\n\n"
598 "instead of\n\n"
599 " {name} = {hint}\n"
600 )
601 nonlocals = get_variables_in_frame_by_scope(frame, "nonlocal")
602
603 scopes = (
604 ("local", frame.f_locals),
605 ("global", frame.f_globals),
606 ("nonlocal", nonlocals),
607 )
608
609 for scope, scope_dict in scopes:
610 if "__annotations__" in scope_dict and name in scope_dict["__annotations__"]:
611 hint = scope_dict["__annotations__"][name]
612 # For Python 3.10+, all type hints are strings
613 if (
614 isinstance(hint, str)
615 and sys.version_info.major == 3
616 and sys.version_info.minor < 10
617 ):
618 hint = repr(hint)
619 return type_hint_found_in_scope.format(name=name, scope=scope, hint=hint)
620
621 return ""