| 1 |
"""config.py |
| 2 |
|
| 3 |
Keep tabs of all settings. |
| 4 |
""" |
| 5 |
|
| 6 |
import sys |
| 7 |
import types |
| 8 |
from typing import List, Optional, Type, Union |
| 9 |
|
| 10 |
from . import base_formatters, core, debug_helper |
| 11 |
from .ft_gettext import current_lang |
| 12 |
from .typing_info import _E, Formatter, InclusionChoice, Info, Writer |
| 13 |
|
| 14 |
_ = current_lang.translate |
| 15 |
|
| 16 |
|
| 17 |
def _write_err(text: Optional[str]) -> None: |
| 18 |
"""Default writer""" |
| 19 |
if text is None: |
| 20 |
return |
| 21 |
if not text.strip(): |
| 22 |
return |
| 23 |
if not text.endswith("\n"): |
| 24 |
text += "\n" |
| 25 |
sys.stderr.write(text) |
| 26 |
|
| 27 |
|
| 28 |
class _State: |
| 29 |
"""Keeping track of various parameters in a single object meant |
| 30 |
to be instantiated only once. |
| 31 |
""" |
| 32 |
|
| 33 |
def __init__(self) -> None: |
| 34 |
self._captured: List[str] = [] |
| 35 |
self.write_err: Writer = _write_err |
| 36 |
self.installed: bool = False |
| 37 |
self.formatter: Formatter = base_formatters.repl |
| 38 |
self.recorded_tracebacks: List[core.FriendlyTraceback] = [] |
| 39 |
self.include: InclusionChoice = "explain" |
| 40 |
self.lang: str = "en" |
| 41 |
self.install_gettext(self.lang) |
| 42 |
self.other_set_lang = [] |
| 43 |
self.suggest_console: str = "\n" + _( |
| 44 |
"Are you using a regular Python console instead of a Friendly console?\n" |
| 45 |
"If so, to continue, try: `start_console(local_vars=locals())`.\n" |
| 46 |
"You will need to import `start_console` if you have not already done so.\n" |
| 47 |
) |
| 48 |
|
| 49 |
self.ipython_prompt: bool = True |
| 50 |
self.exception_before_import: bool = False |
| 51 |
self.sys_last_type = None |
| 52 |
self.sys_last_value = None |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
self.use_rich: bool = False |
| 57 |
self.rich_add_vspace: bool = True |
| 58 |
self.rich_width: Union[int, None] = None |
| 59 |
self.rich_tb_width: Union[int, None] = None |
| 60 |
self.is_jupyter: bool = False |
| 61 |
self.jupyter_button_style: str = "" |
| 62 |
|
| 63 |
self.old_excepthook = None |
| 64 |
|
| 65 |
|
| 66 |
self.include_chained_exception = True |
| 67 |
|
| 68 |
def show_traceback_info_again(self, index: int = -1) -> None: |
| 69 |
"""If has not been cleared, write the traceback info again, using |
| 70 |
the default stream. |
| 71 |
|
| 72 |
This is intended to be used when a user changes the verbosity |
| 73 |
level and wishes to see a traceback reexplained without having |
| 74 |
to execute the code again. |
| 75 |
""" |
| 76 |
if not self.recorded_tracebacks: |
| 77 |
print(_("Nothing to show: no exception recorded.")) |
| 78 |
return |
| 79 |
try: |
| 80 |
info = self.recorded_tracebacks[index].info |
| 81 |
except IndexError: |
| 82 |
print(_("Invalid index value.")) |
| 83 |
return |
| 84 |
if info["lang"] != self.lang: |
| 85 |
self.recorded_tracebacks[index].recompile_info() |
| 86 |
info = self.recorded_tracebacks[index].info |
| 87 |
|
| 88 |
explanation = self.formatter(info, include=self.include) |
| 89 |
self.write_err(explanation) |
| 90 |
|
| 91 |
self.write_err("\n") |
| 92 |
|
| 93 |
def capture(self, txt: str) -> None: |
| 94 |
"""Captures the output instead of writing to stderr.""" |
| 95 |
self._captured.append(txt) |
| 96 |
|
| 97 |
def get_captured(self, flush: bool = True) -> str: |
| 98 |
"""Returns the result of captured output as a string""" |
| 99 |
result = "".join(self._captured) |
| 100 |
if flush: |
| 101 |
self._captured.clear() |
| 102 |
return result |
| 103 |
|
| 104 |
def set_lang(self, lang: str) -> None: |
| 105 |
"""Sets the language.""" |
| 106 |
for fn in self.other_set_lang: |
| 107 |
fn(lang) |
| 108 |
current_lang.install(lang) |
| 109 |
self.lang = lang |
| 110 |
|
| 111 |
def install_gettext(self, lang: str) -> None: |
| 112 |
"""Sets the current language for gettext.""" |
| 113 |
current_lang.install(lang) |
| 114 |
self.lang = lang |
| 115 |
|
| 116 |
def set_include(self, include: InclusionChoice) -> None: |
| 117 |
if include not in base_formatters.items_groups: |
| 118 |
raise ValueError(f"{include} is not a valid value.") |
| 119 |
self.include = include |
| 120 |
|
| 121 |
def get_include(self) -> InclusionChoice: |
| 122 |
return self.include |
| 123 |
|
| 124 |
def set_formatter(self, formatter: Union[str, None, Formatter] = None) -> None: |
| 125 |
"""Sets the default formatter. If no argument is given, the default |
| 126 |
formatter is used. |
| 127 |
""" |
| 128 |
if formatter is None or formatter == "repl": |
| 129 |
self.formatter = base_formatters.repl |
| 130 |
elif formatter == "docs": |
| 131 |
self.formatter = base_formatters.docs |
| 132 |
elif isinstance(formatter, str): |
| 133 |
self.write_err(f"Unknown formatter: {formatter}\n") |
| 134 |
self.formatter = base_formatters.repl |
| 135 |
else: |
| 136 |
self.formatter = formatter |
| 137 |
|
| 138 |
def install( |
| 139 |
self, |
| 140 |
lang: Optional[str] = None, |
| 141 |
redirect: Union[str, Writer, None] = None, |
| 142 |
include: InclusionChoice = None, |
| 143 |
) -> None: |
| 144 |
"""Replaces sys.excepthook by friendly's own version.""" |
| 145 |
|
| 146 |
if lang is not None: |
| 147 |
self.install_gettext(lang) |
| 148 |
if redirect is not None: |
| 149 |
self.set_redirect(redirect=redirect) |
| 150 |
if include is not None: |
| 151 |
self.set_include(include) |
| 152 |
if self.installed: |
| 153 |
return |
| 154 |
|
| 155 |
self.old_excepthook = sys.excepthook |
| 156 |
sys.excepthook = self.exception_hook |
| 157 |
self.installed = True |
| 158 |
|
| 159 |
def uninstall(self) -> None: |
| 160 |
"""Resets sys.excepthook to the excepthook used before installing friendly-traceback.""" |
| 161 |
if not self.installed: |
| 162 |
return |
| 163 |
sys.excepthook = self.old_excepthook |
| 164 |
self.installed = False |
| 165 |
|
| 166 |
def set_redirect(self, redirect: Union[str, Writer, None] = None) -> None: |
| 167 |
"""Sets where the output is redirected.""" |
| 168 |
if redirect == "capture": |
| 169 |
self.write_err = self.capture |
| 170 |
elif redirect is not None: |
| 171 |
self.write_err = redirect |
| 172 |
else: |
| 173 |
self.write_err = _write_err |
| 174 |
|
| 175 |
def explain_traceback(self, redirect: Union[str, Writer, None] = None) -> None: |
| 176 |
"""Replaces a standard traceback by a friendlier one, giving more |
| 177 |
information about a given exception than a standard traceback. |
| 178 |
Note that this excludes SystemExit and KeyboardInterrupt which |
| 179 |
are re-raised. |
| 180 |
|
| 181 |
By default, the output goes to sys.stderr or to some other stream |
| 182 |
set to be the default by another API call. However, if |
| 183 |
redirect = some_stream |
| 184 |
is specified, the output goes to that stream, but without changing |
| 185 |
the global settings. |
| 186 |
""" |
| 187 |
etype, value, tb = sys.exc_info() |
| 188 |
if etype is None: |
| 189 |
if not self.exception_before_import: |
| 190 |
print(_("Nothing to show: no exception recorded.")) |
| 191 |
return |
| 192 |
if not ( |
| 193 |
self.sys_last_type == sys.last_type |
| 194 |
and self.sys_last_value == sys.last_value |
| 195 |
): |
| 196 |
session.get_traceback_info( |
| 197 |
sys.last_type, sys.last_value, sys.last_traceback |
| 198 |
) |
| 199 |
self.sys_last_type = sys.last_type |
| 200 |
self.sys_last_value = sys.last_value |
| 201 |
info = self.recorded_tracebacks[-1].info |
| 202 |
self.output_info(info) |
| 203 |
return |
| 204 |
|
| 205 |
self.exception_before_import = False |
| 206 |
self.exception_hook(etype, value, tb, redirect=redirect) |
| 207 |
|
| 208 |
def exception_hook( |
| 209 |
self, |
| 210 |
etype: Type[_E], |
| 211 |
value: _E, |
| 212 |
tb: types.TracebackType, |
| 213 |
redirect: Union[str, Writer, None] = None, |
| 214 |
) -> None: |
| 215 |
"""Replaces a standard traceback by a friendlier one, |
| 216 |
except for SystemExit and KeyboardInterrupt which |
| 217 |
are re-raised. |
| 218 |
|
| 219 |
The values of the required arguments are typically the following: |
| 220 |
|
| 221 |
etype, value, tb = sys.exc_info() |
| 222 |
|
| 223 |
By default, the output goes to sys.stderr or to some other stream |
| 224 |
set to be the default by another API call. However, if |
| 225 |
redirect = some_stream |
| 226 |
is specified, the output goes to that stream for this call, |
| 227 |
but the session settings is restored afterwards. |
| 228 |
""" |
| 229 |
|
| 230 |
if etype.__name__ == "SystemExit": |
| 231 |
raise SystemExit(str(value)) |
| 232 |
if etype.__name__ == "KeyboardInterrupt": |
| 233 |
raise KeyboardInterrupt(str(value)) |
| 234 |
|
| 235 |
info = self.get_traceback_info(etype, value, tb) |
| 236 |
if not info: |
| 237 |
return |
| 238 |
self.output_info(info, redirect=redirect) |
| 239 |
|
| 240 |
def output_info( |
| 241 |
self, info: dict, redirect: Union[str, Writer, None] = None |
| 242 |
) -> None: |
| 243 |
"""Outputs the information obtained from a traceback. |
| 244 |
|
| 245 |
By default, the output goes to sys.stderr or to some other stream |
| 246 |
set to be the default by another API call. However, if |
| 247 |
redirect = some_stream |
| 248 |
is specified, the output goes to that stream for this call, |
| 249 |
but the session settings is restored afterwards. |
| 250 |
""" |
| 251 |
saved_current_redirect = None |
| 252 |
if redirect is not None: |
| 253 |
saved_current_redirect = self.write_err |
| 254 |
self.set_redirect(redirect=redirect) |
| 255 |
|
| 256 |
explanation = self.formatter(info, include=self.include) |
| 257 |
self.write_err(explanation) |
| 258 |
|
| 259 |
|
| 260 |
if hasattr(explanation, "endswith") and not explanation.endswith("\n"): |
| 261 |
self.write_err("\n") |
| 262 |
|
| 263 |
if saved_current_redirect is not None: |
| 264 |
self.set_redirect(redirect=saved_current_redirect) |
| 265 |
|
| 266 |
def get_traceback_info( |
| 267 |
self, |
| 268 |
etype: Type[_E], |
| 269 |
value: _E, |
| 270 |
tb: types.TracebackType, |
| 271 |
) -> Info: |
| 272 |
"""Obtains the information available after a traceback has been raised. |
| 273 |
|
| 274 |
The values of the required arguments are typically the following: |
| 275 |
|
| 276 |
etype, value, tb = sys.exc_info() |
| 277 |
|
| 278 |
Returns a dict containing the available info. |
| 279 |
""" |
| 280 |
try: |
| 281 |
self.recorded_tracebacks.append(core.FriendlyTraceback(etype, value, tb)) |
| 282 |
self.recorded_tracebacks[-1].compile_info() |
| 283 |
info = self.recorded_tracebacks[-1].info |
| 284 |
except Exception: |
| 285 |
if not debug_helper.DEBUG: |
| 286 |
print( |
| 287 |
"Exception raised by friendly-traceback. Please report this case." |
| 288 |
) |
| 289 |
return {} |
| 290 |
debug_helper.log("Exception raised in get_traceback_info().") |
| 291 |
raise |
| 292 |
return info |
| 293 |
|
| 294 |
|
| 295 |
session = _State() |
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
def did_exception_occur_before() -> bool: |
| 301 |
"""If an exception occurred before friendly-traceback was imported, it captures |
| 302 |
the information and prints an informative message to the user. |
| 303 |
|
| 304 |
Returns True if such information was captures, False otherwise. |
| 305 |
""" |
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
def _exception_occurred(): |
| 317 |
return _( |
| 318 |
"An exception occurred before friendly-traceback was imported.\n" |
| 319 |
"Some information is available." |
| 320 |
) |
| 321 |
|
| 322 |
if ( |
| 323 |
hasattr(sys, "last_type") |
| 324 |
and hasattr(sys, "last_type") |
| 325 |
and hasattr(sys, "last_traceback") |
| 326 |
): |
| 327 |
_info = session.get_traceback_info( |
| 328 |
sys.last_type, sys.last_value, sys.last_traceback |
| 329 |
) |
| 330 |
if _info: |
| 331 |
session.sys_last_type = sys.last_type |
| 332 |
session.sys_last_value = sys.last_value |
| 333 |
if not session.exception_before_import: |
| 334 |
print(_exception_occurred()) |
| 335 |
session.exception_before_import = True |
| 336 |
return True |
| 337 |
return False |