Debian Codegraph @

friendly_traceback/__init__.py

raw symbols SCIP
1 """
2 With the exceptions of the functions that are specific to the console,
3 this module contains all the functions that are part of the public API.
4 While Friendly-traceback is still considered to be in beta stage,
5 we do attempt to avoid creating incompatibility for the functions
6 here when introducing changes.
7
8 The goal is to be even more careful to avoid introducing incompatibilities
9 when reaching beta stage, and planning to be always backward compatible
10 starting at version 1.0 -- except possibly for the required minimal
11 Python version.
12
13 Friendly-traceback is currently compatible with Python versions 3.6
14 or newer.
15
16 If you find that some additional functionality would be useful to
17 have as part of the public API, please let us know.
18 """
19
20 import contextlib
21
22 with contextlib.suppress(ImportError, ModuleNotFoundError):
23 import readline # noqa issue 80; ImportError added for Pypy.
24
25 import os
26 import sys
27 from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union
28
29 valid_version = sys.version_info >= (3, 6)
30
31 if not valid_version: # pragma: no cover
32 print("Python 3.6 or newer is required.")
33 sys.exit()
34
35 __version__ = "0.7.62"
36
37 # ===========================================
38
39 import inspect
40 from pathlib import Path
41
42 from . import base_formatters, debug_helper, editors_helpers, info_variables, path_info
43 from .about_warnings import enable_warnings # noqa
44 from .about_warnings import IGNORE_WARNINGS
45 from .config import session
46 from .ft_gettext import current_lang
47 from .runtime_errors import modules_attributes, third_party_names
48 from .source_cache import friendly_exec # noqa
49 from .typing_info import Formatter, InclusionChoice, StrPath, Writer
50
51 # See https://github.com/friendly-traceback/friendly-traceback/issues/207
52 _writing_docs = False # noqa
53
54
55 def add_ignored_warnings(do_not_show_warning: Callable[[Any], bool]) -> None:
56 """Adds a function which will be passed
57 ``warning_instance, warning_type, filename, lineno`` as arguments
58 when a warning is raised. If this function returns ``True``, the
59 warning will be ignored.
60
61 This is intended for third-party packages that might trigger warnings
62 which should not be shown to a user of friendly_traceback.
63 """
64 IGNORE_WARNINGS.add(do_not_show_warning)
65
66
67 def add_other_attribute_names(attributes: Dict) -> None:
68 """Intended for extension to friendly_traceback that provide support for
69 some other modules. An example is friendly_pandas. These names can be
70 used as suggestion in case of a NameError, suggesting that a given
71 module (name) should perhaps be imported.
72
73 Args:
74 attributes: A dict with attribute names used as keys and a sequence of
75 modules containing such attributes. An example from the
76 standard library might be::
77
78 attributes = {"cos": ["cmath", "math"],
79 "sin": ["cmath", "math"] }
80 """
81 attr_names = modules_attributes.attribute_names
82 for attribute in attributes:
83 if attribute not in attr_names:
84 attr_names[attribute] = list(attributes[attribute])
85 else:
86 attr_names[attribute].extend(list(attributes[attribute]))
87
88
89 def add_other_module_names_synonyms(synonyms: Dict) -> None:
90 """Intended for extension to friendly_traceback that provide support for
91 some other modules. An example is friendly_pandas. These names can be
92 used as suggestion in case of a NameError, suggesting that a given
93 module (name) should perhaps be imported. For example, given
94 ``names = {"np": "numpy"}``, if ``np`` is an unknown name, the suggestion
95 would include ``import numpy as np``
96
97 Args:
98 synonyms: a dict containing synonyms often used for module names imported.
99 For example:
100 ``synonyms = {"np": "numpy"}``
101 """
102 third_party_names.module_synonyms.update(**synonyms)
103
104
105 def add_other_set_lang(func: Callable[[str], None]) -> None:
106 """Intended for extension to friendly_traceback that can also do translations.
107
108 Args:
109 func: a callable that should be invoked when ``set_lang`` is called to
110 also set the language of the extension.
111 """
112 session.other_set_lang.append(func)
113
114
115 def exclude_file_from_traceback(full_path: StrPath) -> None:
116 """Exclude a file from appearing in a traceback generated by
117 Friendly.
118 Note that this does not apply to the true Python traceback
119 obtained using ``"debug_tb"`` in interactive mode.
120
121 Args:
122 full_path: the path of the file to exclude from the traceback.
123 """
124 path_info.exclude_file_from_traceback(full_path)
125
126
127 def exclude_directory_from_traceback(dir_name: StrPath) -> None:
128 """Exclude all files found in a given directory, including subdirectories,
129 from appearing in a traceback generated by Friendly.
130 Note that this does not apply to the true Python traceback
131 obtained using ``"debug_tb"``.
132
133 Args:
134 dir_name: the path representing the directory to exclude.
135 """
136 path_info.exclude_directory_from_traceback(dir_name)
137
138
139 def explain_traceback(redirect: Union[str, Writer, None] = None) -> None:
140 """Replaces a standard traceback by a friendlier one, giving more
141 information about a given exception than a standard traceback.
142 Note that this excludes ``SystemExit`` and ``KeyboardInterrupt``
143 which are re-raised.
144
145 Args:
146 redirect: some specified stream. By default, the output goes to
147 ``sys.stderr``. If the string ``"capture"`` is given as the value
148 for ``redirect``, the output is saved and can be later retrieved
149 by ``get_output()``.
150 """
151 session.explain_traceback(redirect=redirect)
152
153
154 def hide_secrets(patterns: Union[List[str], None] = None) -> None:
155 """Intended to prevent values of certain variables to be shown.
156
157 Args:
158
159 patterns: a list of regular expression patterns.
160 """
161 info_variables.confidential.hide_confidential_information(patterns=patterns)
162
163
164 def test_secrets(name: str = "") -> Union[str, None]:
165 """Given a variable name that exists in the local scope where this function is invoked
166 returns the value that will be shown if the variable value needs to be
167 shown in a traceback.
168 """
169 frame = inspect.getouterframes(inspect.currentframe())[1].frame
170 if name not in frame.f_locals:
171 print(
172 "The argument of test_secrets must be a string representing the name of a local object."
173 )
174 return None
175 obj = frame.f_locals[name]
176 return info_variables.format_var_info(name, obj)
177
178
179 def get_output(flush: bool = True) -> str:
180 """Returns the result of captured output as a string which can be
181 written anywhere desired.
182
183 Args:
184 flush: True y default, flushes all the captured content.
185
186 """
187 return session.get_captured(flush=flush)
188
189
190 def install(
191 lang: Optional[str] = None,
192 redirect: Union[str, Writer, None] = None,
193 include: InclusionChoice = "explain",
194 _debug: Optional[bool] = False,
195 ) -> None:
196 """
197 Replaces ``sys.excepthook`` by friendly's own version.
198 Intercepts, and can provide an explanation for all Python exceptions except
199 for ``SystemExist`` and ``KeyboardInterrupt``.
200
201 Args:
202 lang: language to be used for translations. If not available,
203 English will be used as a default.
204 redirect: stream to be used to send the output.
205 The default is ``sys.stderr``.
206 include: controls the amount of information displayed.
207 See ``set_include()`` for details.
208 _debug: optional argument that can be used to enable some debugging
209 features.
210
211 """
212 if _debug: # Note that the debugging mode can be set via other methods
213 debug_helper.DEBUG = _debug
214 session.install(lang=lang, redirect=redirect, include=include)
215
216
217 def is_installed() -> bool:
218 """Returns True if friendly_traceback is installed, False otherwise."""
219 return session.installed
220
221
222 def uninstall() -> None:
223 """Resets ``sys.excepthook`` to Python's default."""
224 session.uninstall()
225
226
227 def run(
228 filename: StrPath,
229 lang: str = "en",
230 include: Optional[InclusionChoice] = None,
231 args: Optional[Sequence[str]] = None,
232 console: Optional[bool] = True,
233 formatter: Optional[Union[str, Formatter]] = "repl",
234 redirect: Optional[Union[str, Writer]] = None,
235 ipython_prompt: bool = True,
236 ) -> Optional[Dict[str, Any]]: # sourcery skip: move-assign
237 """Given a filename (relative or absolute path) ending with the ".py"
238 extension, this function executes the code in the file.
239
240 If console is set to ``False``, ``run()`` returns an empty dict
241 if a ``SyntaxError`` was raised, otherwise returns the dict in
242 which the module (``filename``) was executed.
243
244 If console is set to ``True`` (the default), the execution continues
245 as an interactive session in a Friendly console, with the module
246 dict being used as the ``locals()`` dict.
247
248 Args:
249 lang: language used; currently 'en' (default), 'fr', 'es', 'ta',
250 'ru', 'it', 'he' are available.
251 include: specifies what information is to be included if an
252 exception is raised; the default is "friendly_tb" if console
253 is set to True, otherwise it is "explain"
254 args: strings tuple that is passed to the program as though it
255 was run on the command line as follows::
256
257 python filename.py arg1 arg2 ...
258 """
259 _ = current_lang.translate
260 if include is None:
261 include = "friendly_tb" if console else "explain"
262 if args is not None:
263 sys.argv = [str(filename), *list(args)]
264 else:
265 filename = Path(filename)
266 if not filename.is_absolute():
267 frame = inspect.stack()[1]
268 # This is the file from which run() is called
269 run_filename = Path(frame[0].f_code.co_filename)
270 run_dir = run_filename.parent.absolute()
271 filename = run_dir.joinpath(filename)
272
273 if not filename.exists():
274 print(_("The file {filename} does not exist.").format(filename=filename))
275 return {}
276
277 session.install(lang=lang, include=include, redirect=redirect)
278 session.set_formatter(formatter)
279
280 module_globals = editors_helpers.exec_code(
281 path=filename, lang=lang, include=include
282 )
283 if console: # pragma: no cover
284 start_console(
285 local_vars=module_globals,
286 formatter=formatter,
287 banner="",
288 include=include,
289 lang=lang,
290 ipython_prompt=ipython_prompt,
291 )
292 else:
293 return module_globals
294
295
296 def set_formatter(formatter: Union[str, None, Formatter] = None) -> None:
297 """Sets the default formatter. If no argument is given, the default
298 formatter is used.
299 """
300 session.set_formatter(formatter=formatter)
301
302
303 def start_console( # pragma: no cover
304 local_vars: Optional[Mapping[str, Any]] = None,
305 formatter: Union[str, Formatter] = None,
306 include: InclusionChoice = "friendly_tb",
307 lang: str = "en",
308 banner: Optional[str] = None,
309 displayhook: Optional[Callable[[object], Any]] = None,
310 ipython_prompt: bool = True,
311 ) -> None:
312 """Starts a Friendly console."""
313 from . import ft_console
314
315 ft_console.start_console(
316 local_vars=local_vars,
317 formatter=formatter,
318 include=include,
319 lang=lang,
320 banner=banner,
321 displayhook=displayhook,
322 ipython_prompt=ipython_prompt,
323 )
324
325
326 # =========================================================================
327 # Below, we have many set_X()/get_X() pairs. The only reason why we include
328 # the get_X() type of functions is to make it possible to make some
329 # temporary changes, i.e.
330 #
331 # saved = get_x()
332 # set_X(something)
333 # do_something()
334 # set_X(saved)
335 # =========================================================================
336
337
338 def set_lang(lang: str = "en") -> Union[List[str], None]:
339 """Sets the language to be used for the display.
340
341 Args:
342 lang: If no translations exist for that language, the original
343 English strings will be used.
344 If a value of ``None`` is used, a list of
345 available languages is returned.
346
347 """
348 _ = current_lang.translate
349 if lang is None:
350 languages = [
351 language
352 for language in os.listdir(
353 os.path.join(os.path.dirname(__file__), "locales")
354 )
355 if not language.endswith(".pot")
356 ]
357 print(_("The available languages are:"), languages)
358 return
359 session.set_lang(lang=lang)
360
361
362 def get_lang() -> str:
363 """Returns the current language that had been set for translations.
364
365 Note that the value returned may not reflect truly what is being
366 seen by the end user: if the translations do not exist for that language,
367 the default English strings are used.
368 """
369 return session.lang
370
371
372 _include_choices = [key for key in base_formatters.items_groups if key != "header"]
373
374
375 def set_include(include: InclusionChoice) -> None:
376 """Specifies the information to include in the traceback.
377
378 Args:
379 include: one of the following allowed values: {choices}
380 """
381 _ = current_lang.translate
382
383 # TODO: add unit test for invalid choice
384 if include not in _include_choices:
385 print(_("{include}: Unrecognized value.").format(include=include))
386 print(_("The allowed values are:"), _include_choices)
387 return
388 session.set_include(include)
389
390
391 if set_include.__doc__ is not None: # protect against -OO optimization
392 _choices = ", ".join(_include_choices)
393 set_include.__doc__ = set_include.__doc__.format(choices=_choices)
394
395
396 def get_include() -> InclusionChoice:
397 """Retrieves the single string value used to determine what to include in the
398 traceback. See ``set_include()`` for details.
399 """
400 return session.get_include()
401
402
403 def set_stream(redirect: Union[str, Writer, None] = None) -> None:
404 """Sets the stream to which the output should be directed.
405
406 Args:
407 redirect: if the string ``"capture"`` is given as argument, the
408 output is saved and can be later retrieved by ``get_output()``.
409 If no argument is given, the default stream (``stderr``) is set.
410 """
411 session.set_redirect(redirect=redirect)
412
413
414 def get_stream() -> Writer:
415 """Returns the value of the current stream used for output."""
416 return session.write_err
417
418
419 del Any, Callable, Dict, Mapping, Optional, Sequence, Union
420 del Formatter, InclusionChoice, StrPath, Writer
421 del valid_version