Debian Codegraph @

friendly_traceback/console_helpers.py

raw symbols SCIP
1 """
2 This module includes functions that can be used in a friendly console
3 or in other **interactive** environments such as in a Jupyter notebook.
4
5 If you intend to use ``friendly_traceback`` in an interactive environment,
6 you should use ``friendly`` instead, as in::
7
8 from friendly.ipython import ...
9 # or
10 from friendly.jupyter import ...
11 # etc.
12
13 Since this documentation is generated automatically by Sphinx using
14 ``friendly_traceback`` code, it will not contain all the relevant
15 functions specific to a given environment. To find out about what
16 functions are available in such environments, do the following::
17
18 prompt>> from friendly.X import Friendly
19 prompt>> Friendly
20 # The output will include the required information
21 """
22
23 # NOTE: __all__ is defined at the very bottom of this file
24 import inspect
25 import sys
26 import types
27 from typing import Any, Callable, Dict, List, Optional, Type, Union
28
29 import friendly_traceback
30 from friendly_traceback import __version__, base_formatters, debug_helper
31 from friendly_traceback.config import session
32 from friendly_traceback.ft_gettext import current_lang
33 from friendly_traceback.functions_help import add_help_attribute
34 from friendly_traceback.info_generic import get_generic_explanation
35 from friendly_traceback.path_info import show_paths
36 from friendly_traceback.syntax_errors.source_info import Statement
37 from friendly_traceback.tb_data import TracebackData
38 from friendly_traceback.typing_info import InclusionChoice, Site
39
40 _ = current_lang.translate
41
42
43 def _nothing_to_show():
44 return _("Nothing to show: no exception recorded.")
45
46
47 def disable():
48 """Disable friendly-traceback exception hook"""
49 if not session.installed:
50 info = {"suggest": _("Friendly-traceback is already disabled.") + "\n"}
51 explanation = session.formatter(info, include="hint")
52 session.write_err(explanation)
53 return
54 session.uninstall()
55
56
57 def enable():
58 """Enable friendly-traceback exception hook"""
59 if session.installed:
60 info = {"suggest": _("Friendly-traceback is already enabled.") + "\n"}
61 explanation = session.formatter(info, include="hint")
62 session.write_err(explanation)
63 return
64 session.install()
65
66
67 def explain(index: int = -1, include: InclusionChoice = "explain") -> None:
68 """Shows the previously recorded traceback info again,
69 with the option to specify different items to include.
70 For example, ``explain("why")`` is equivalent to ``why()``.
71 """
72 old_include = friendly_traceback.get_include()
73 friendly_traceback.set_include(include)
74 session.show_traceback_info_again(index)
75 friendly_traceback.set_include(old_include)
76
77
78 def friendly_tb(index: int = -1) -> None:
79 """Shows the simplified Python traceback,
80 which includes the hint/suggestion if available.
81 """
82 explain(index, include="friendly_tb")
83
84
85 def hint(index: int = -1) -> None:
86 """Shows hint/suggestion if available."""
87 explain(index, include="hint")
88
89
90 class History:
91 __name__ = "history"
92
93 def __call__(self):
94 """Prints a list of recorded tracebacks and warning messages"""
95 if not session.recorded_tracebacks:
96 info = {"suggest": _nothing_to_show() + "\n"}
97 explanation = session.formatter(info, include="hint")
98 session.write_err(explanation)
99 return
100 session.rich_add_vspace = False # for friendly
101 for index, tb in enumerate(session.recorded_tracebacks):
102 if "message" in tb.info:
103 info = {"message": f"{index}. {tb.info['message']}"}
104 explanation = session.formatter(info, include="message")
105 session.write_err(explanation)
106 session.rich_add_vspace = True
107
108 def __repr__(self):
109 return (
110 _("Shows a list of recorded traceback messages.")
111 + "\n"
112 + _("You can also use `history.clear()` and `history.pop()`.")
113 )
114
115 def clear(self):
116 """Removes all recorded tracebacks and warnings"""
117 session.recorded_tracebacks.clear()
118
119 def pop(self, index=-1):
120 """Used to delete a particular item, with the last item removed by default"""
121 if not session.recorded_tracebacks:
122 info = {"suggest": _("Nothing to delete: no exception recorded.") + "\n"}
123 explanation = session.formatter(info, include="hint")
124 session.write_err(explanation)
125 return
126 try:
127 session.recorded_tracebacks.pop(index)
128 except IndexError:
129 info = {"suggest": _("There is no such history item.") + "\n"}
130 explanation = session.formatter(info, include="hint")
131 session.write_err(explanation)
132
133
134 history = History()
135
136
137 def python_tb(index: int = -1) -> None:
138 """Shows the Python traceback, excluding files from friendly
139 itself.
140 """
141 explain(index, include="python_tb")
142
143
144 def what(
145 exception_or_index: Union[
146 Type[BaseException], str, bytes, types.CodeType, int, None
147 ] = None,
148 pre: bool = False,
149 ) -> None:
150 """If known, shows the generic explanation about a given exception.
151
152 If the ``pre`` argument is set to ``True``, the output is
153 formatted in a way that is suitable for inclusion in the
154 documentation.
155 """
156 if exception_or_index is None:
157 explain(index=-1, include="what")
158 return
159 elif isinstance(exception_or_index, int):
160 explain(index=exception_or_index, include="what")
161 return
162
163 if inspect.isclass(exception_or_index) and issubclass(
164 exception_or_index, BaseException
165 ):
166 result = get_generic_explanation(exception_or_index)
167 else:
168 try:
169 exc = eval(exception_or_index) # skipcq PYL-W0123
170 if inspect.isclass(exc) and issubclass(exc, BaseException):
171 result = get_generic_explanation(exc)
172 else:
173 result = _("{exception} is not an exception.").format(
174 exception=f"`{exception_or_index}`"
175 )
176 except Exception: # noqa
177 result = _("{exception} is not an exception.").format(
178 exception=f"`{exception_or_index}`"
179 )
180
181 if pre: # for documentation # pragma: no cover
182 lines = result.split("\n")
183 for line in lines:
184 session.write_err(f" {line}\n")
185 session.write_err("\n")
186 else:
187 info = {"generic": result}
188 explanation = session.formatter(info, include="what")
189 session.write_err(explanation)
190
191
192 def where(index: int = -1, more=False) -> None:
193 """Shows the information about where the exception occurred"""
194 if more:
195 try:
196 info = session.recorded_tracebacks[index].info
197 except Exception:
198 explain(index, "where") # let the error bubble up
199 else:
200 if "detailed_tb" in info:
201 explain(index, "detailed_tb")
202 else:
203 explain(index, "where")
204 else:
205 explain(index, "where")
206
207
208 def why(index: int = -1) -> None:
209 """Shows the likely cause of the exception."""
210 # If no cause is found, and the exception name is not accompanied by a
211 # message, as in "StopIteration:", we use the same info for
212 # the cause as we used for the generic information as per issue #66
213 try:
214 if index == -1:
215 info = session.recorded_tracebacks[-1].info
216 else:
217 info = session.recorded_tracebacks[index + 1].info
218 except IndexError:
219 info = {}
220 if (
221 ("cause" not in info or not info["cause"])
222 and "message" in info
223 and len(info["message"].split(":")) > 1
224 and not info["message"].split(":")[1].strip() # empty message
225 ):
226 explain(index, "what")
227 else:
228 explain(index, "why")
229
230
231 def www(site_or_index: Union[Site, int] = -1) -> None: # pragma: no cover
232 """This uses the ``webbrowser`` module to open a tab (or window)
233 in the default browser, linking to a specific url
234 or opening the default email client.
235
236 * If the argument ``site_or_index`` is not specified,
237 and an exception or a warning has been raised,
238 an internet search will be done using
239 the exception message of the last exception or warning
240 as the search string.
241
242 * If the argument ``site_or_index`` is not specified,
243 and NO exception has been raised,
244 Friendly's documentation will open.
245
246 * If the argument ``site_or_index`` == "friendly",
247 Friendly's documentation will open.
248
249 * If the argument ``site_or_index`` == "python", Python's documentation site
250 will open with the currently used Python version.
251
252 * If the argument ``site_or_index`` == "bug",
253 the Issues page for Friendly on GitHub will open.
254
255 * If the argument ``site_or_index`` == "email",
256 the default email client should open with Friendly's
257 developer's address already filled in.
258
259 * If the argument ``site_or_index`` is an integer representing an item
260 in the recorded history, an internet search will be done using
261 the exception message of the corresponding item as the search string.
262 """
263 import urllib.parse
264 import webbrowser
265
266 def open_browser(url):
267 try:
268 webbrowser.open_new_tab(url)
269 except Exception: # noqa
270 session.write_err(
271 _("The default web browser cannot be used for searching.")
272 )
273 return
274
275 urls: Dict[Site, str] = {
276 "friendly": "https://friendly-traceback.github.io/docs/index.html",
277 "python": f"https://docs.python.org/3.{sys.version_info.minor}/",
278 "bug": "https://github.com/friendly-traceback/friendly-traceback/issues/new",
279 "email": "mailto:[email protected]",
280 }
281 invalid_args = _(
282 "Invalid argument for `www()`.\n"
283 "Valid arguments are integer values or one of `{sites}`.\n"
284 ).format(sites=repr(urls.keys()))
285
286 if isinstance(site_or_index, int):
287 index = site_or_index
288 else:
289 try:
290 site = site_or_index.casefold()
291 except Exception: # noqa
292 session.write_err(invalid_args)
293 return
294 else:
295 if site not in urls:
296 session.write_err(invalid_args)
297 return
298 return open_browser(urls[site])
299
300 try:
301 info = (
302 session.recorded_tracebacks[index].info
303 if session.recorded_tracebacks
304 else {}
305 )
306 except IndexError:
307 session.write_err(_("Invalid index value."))
308 return
309
310 url = urls["friendly"]
311 if info:
312 message = info["message"].replace("'", "")
313 if " (" in message:
314 message = message.split("(")[0]
315 url = f"https://duckduckgo.com?q={urllib.parse.quote(message)}"
316
317 return open_browser(url)
318
319
320 def set_debug(flag: bool = True) -> None: # pragma: no cover
321 """This sets the value of the debug flag for the current session."""
322 debug_helper.DEBUG = flag
323 debug_helper.SHOW_DEBUG_HELPER = flag
324
325
326 get_lang = friendly_traceback.get_lang
327 set_lang = friendly_traceback.set_lang
328 get_include = friendly_traceback.get_include
329 set_include = friendly_traceback.set_include
330 set_formatter = friendly_traceback.set_formatter
331
332 # ===== Debugging functions are not unit tested by choice =====
333
334
335 def _get_statement() -> Optional[Statement]: # pragma: no cover
336 """This returns a 'Statement' instance obtained for SyntaxErrors and
337 subclasses. Such a Statement instance contains essentially all
338 the known information about the statement where the error occurred.
339
340 This is not intended for end-users but is useful in development.
341 """
342 if not session.recorded_tracebacks:
343 print(_nothing_to_show())
344 return None
345 current_tb = session.recorded_tracebacks[-1]
346 if hasattr(current_tb, "tb_data"):
347 if isinstance(
348 session.recorded_tracebacks[-1].tb_data.exception_instance, SyntaxError
349 ):
350 return session.recorded_tracebacks[-1].tb_data.statement
351 elif hasattr(current_tb, "problem_statement"):
352 return current_tb.problem_statement
353 print("No statement: likely not a SyntaxError nor a SyntaxWarning.")
354 return None
355
356
357 def _get_tb_data() -> Optional[TracebackData]: # pragma: no cover
358 """This returns the TracebackData instance containing all the
359 information we have obtained.
360
361 This is not intended for end-users but is useful in development.
362 """
363 if not session.recorded_tracebacks:
364 print(_nothing_to_show())
365 return None
366 current_tb = session.recorded_tracebacks[-1]
367 return current_tb.tb_data if hasattr(current_tb, "tb_data") else current_tb
368
369
370 def _get_info() -> list:
371 """Debugging tool: returns the content of a traceback info."""
372 return session.recorded_tracebacks[-1].info if session.recorded_tracebacks else []
373
374
375 def _show_info() -> None: # pragma: no cover
376 """Debugging tool: shows the complete content of traceback info.
377
378 Prints ``''`` for a given item if it is not present.
379 """
380 info = session.recorded_tracebacks[-1].info if session.recorded_tracebacks else []
381
382 for item in base_formatters.items_in_order:
383 if item in info and info[item].strip():
384 print(f"{item}:")
385 for line in info[item].strip().split("\n"):
386 print(" ", line)
387 print()
388 else:
389 print(f"{item}: ''")
390
391 for item in info:
392 if item not in base_formatters.items_in_order:
393 print(f"{item}: {info[item]}")
394
395
396 helpers: Dict[str, Callable[..., None]] = {
397 "why": why,
398 "what": what,
399 "where": where,
400 "www": www,
401 "explain": explain,
402 "hint": hint,
403 "enable": enable,
404 "disable": disable,
405 "history": history,
406 "friendly_tb": friendly_tb,
407 "python_tb": python_tb,
408 "show_paths": show_paths,
409 "get_include": get_include,
410 "set_include": set_include,
411 "get_lang": get_lang,
412 "set_lang": set_lang,
413 "set_formatter": set_formatter,
414 "set_debug": set_debug,
415 }
416 add_help_attribute(helpers)
417
418 debug_helper_methods: Dict[str, Callable[..., Any]] = {
419 "_get_info": _get_info,
420 "_get_tb_data": _get_tb_data,
421 "_get_statement": _get_statement,
422 }
423 add_help_attribute(debug_helper_methods)
424
425
426 class FriendlyHelpers:
427 """Helper class which can be used in a console as an alternative
428 to using the helper functions directly.
429 This can be helpful if one of the helper functions gets redefined.
430
431 It is usually instantiated using the name ``Friendly``.
432
433 For example, we can write ``Friendly.why()`` as equivalent to ``why()``.
434 """
435
436 version = __version__
437
438 def __init__(self) -> None:
439 self.helpers = {}
440
441 def add_helper(self, function: Callable) -> None: # pragma: no cover
442 """Adds a helper base on its name and the function it refers to."""
443 self.helpers[function.__name__] = function
444 setattr(self, function.__name__, function)
445
446 def remove_helper(self, name: str) -> None: # pragma: no cover
447 """Removes a helper from the FriendlyHelpers object"""
448 if name in self.helpers:
449 del self.helpers[name]
450 delattr(self, name)
451 else:
452 message = f"Cannot remove {name}; it is not a known helper."
453 debug_helper.log(message)
454
455 def __dir__(self) -> List[str]: # pragma: no cover
456 """Only include useful friendly methods."""
457 return sorted(list(self.helpers))
458
459 def __repr__(self) -> str: # pragma: no cover
460 """Shows a brief description in the default language of what
461 each function/method does.
462
463 Debugging helper functions are only included if the DEBUG flag is set.
464 """
465 basic_helpers = {}
466 _debug_helpers = {}
467 for name in self.helpers:
468 if name.startswith("_"):
469 _debug_helpers[name] = self.helpers[name]
470 else:
471 basic_helpers[name] = self.helpers[name]
472
473 # sort alphabetically, then by length name for nicer display
474 basic_helpers = sorted(list(basic_helpers))
475 basic_helpers = sorted(basic_helpers, key=len)
476 _debug_helpers = sorted(list(_debug_helpers))
477 _debug_helpers = sorted(_debug_helpers, key=len)
478
479 header = _(
480 "The following methods of the Friendly object should also "
481 "be available as functions."
482 )
483 parts = [self.true_repr() + "\n" + header + "\n\n"]
484 for name in basic_helpers:
485 parts.append(name + "(): ")
486 fn = self.helpers[name]
487 if hasattr(fn, "help"):
488 parts.append(fn.help() + "\n")
489 else:
490 print("Warning:", name, "has no help() method.")
491
492 if debug_helper.SHOW_DEBUG_HELPER:
493 more_header = "Debugging methods (English only)."
494 parts.append("\n" + more_header + "\n\n")
495 for name in _debug_helpers:
496 parts.append(name + "(): ")
497 fn = self.helpers[name]
498 if hasattr(fn, "help"):
499 parts.append(fn.help() + "\n")
500 else:
501 print("Warning:", name, "has no help() method.")
502 return "".join(parts)
503
504 def true_repr(self) -> str: # pragma: no cover
505 """Method that can be called when a normal looking repr is needed."""
506 return "<class FriendlyHelpers>"
507
508
509 Friendly = FriendlyHelpers()
510 for helper_name in helpers:
511 Friendly.add_helper(helpers[helper_name])
512 for helper_name in debug_helper_methods:
513 Friendly.add_helper(debug_helper_methods[helper_name])
514
515 helpers["Friendly"] = Friendly
516 # We don't include the debug helpers in __all__ so that they do
517 # not show when doing dir() at a console; we only make them
518 # available as methods of the Friendly object.
519 __all__ = list(helpers.keys())