| 1 |
"""This module includes all relevant classes and functions so that |
| 2 |
friendly-traceback can give help with warnings. |
| 3 |
|
| 4 |
It contains one function (``enable_warnings``) which is part of the API, |
| 5 |
and one (``get_warning_parser``) which is the only other function in this module |
| 6 |
which is intended to be part of the public API. However, while the latter |
| 7 |
can be imported using ``from friendly_traceback import enable_warnings``, |
| 8 |
``get_warning_parser`` needs to be imported from this module. |
| 9 |
""" |
| 10 |
|
| 11 |
import inspect |
| 12 |
import warnings |
| 13 |
from importlib import import_module |
| 14 |
from typing import List, Type |
| 15 |
|
| 16 |
import executing |
| 17 |
from stack_data import BlankLines, Formatter, Options |
| 18 |
|
| 19 |
from .config import session |
| 20 |
from .frame_info import FriendlyFormatter |
| 21 |
from .ft_gettext import current_lang, internal_error |
| 22 |
from .info_generic import get_generic_explanation |
| 23 |
from .info_variables import get_var_info |
| 24 |
from .path_info import path_utils |
| 25 |
from .typing_info import _E, CauseInfo, Parser |
| 26 |
|
| 27 |
_ = current_lang.translate |
| 28 |
_warnings_seen = {} |
| 29 |
_RUNNING_TESTS = False |
| 30 |
IGNORE_WARNINGS = set() |
| 31 |
|
| 32 |
|
| 33 |
def enable_warnings(testing: bool = False) -> None: |
| 34 |
"""Used to enable all warnings, with 'always' being used as the |
| 35 |
parameter for warnings.simplefilter. |
| 36 |
|
| 37 |
While friendly_traceback, used by many third-party packages, does not |
| 38 |
automatically handle warnings by default, friendly, which is meant to |
| 39 |
be used by end-users instead of other packages/libraries, does call |
| 40 |
enable_warnings by default. |
| 41 |
""" |
| 42 |
|
| 43 |
|
| 44 |
global _RUNNING_TESTS |
| 45 |
_RUNNING_TESTS = testing |
| 46 |
warnings.simplefilter("always") |
| 47 |
warnings.showwarning = show_warning |
| 48 |
|
| 49 |
|
| 50 |
class MyFormatter(Formatter): |
| 51 |
def format_frame(self, frame): |
| 52 |
yield from super().format_frame(frame) |
| 53 |
|
| 54 |
|
| 55 |
class WarningInfo: |
| 56 |
def __init__( |
| 57 |
self, warning_instance, warning_type, filename, lineno, frame=None, lines=None |
| 58 |
): |
| 59 |
self.warning_instance = warning_instance |
| 60 |
self.message = str(warning_instance) |
| 61 |
self.warning_type = warning_type |
| 62 |
self.filename = filename |
| 63 |
self.lineno = lineno |
| 64 |
self.begin_lineno = lineno |
| 65 |
self.lines = lines |
| 66 |
self.frame = frame |
| 67 |
self.info = {"warning_message": f"{warning_type.__name__}: {self.message}\n"} |
| 68 |
self.info["message"] = self.info["warning_message"] |
| 69 |
|
| 70 |
if frame is not None: |
| 71 |
source = self.format_source() |
| 72 |
self.info["warning_source"] = source |
| 73 |
self.problem_statement = executing.Source.executing(frame).text() |
| 74 |
var_info = get_var_info(self.problem_statement, frame) |
| 75 |
self.info["warning_variables"] = var_info["var_info"] |
| 76 |
if "additional_variable_warning" in var_info: |
| 77 |
self.info["additional_variable_warning"] = var_info[ |
| 78 |
"additional_variable_warning" |
| 79 |
] |
| 80 |
else: |
| 81 |
self.info["warning_source"] = self.get_source_frame_missing() |
| 82 |
self.recompile_info() |
| 83 |
|
| 84 |
def recompile_info(self): |
| 85 |
self.info["lang"] = session.lang |
| 86 |
self.info["generic"] = get_generic_explanation(self.warning_type) |
| 87 |
short_filename = path_utils.shorten_path(self.filename) |
| 88 |
if "[" in short_filename: |
| 89 |
location = _( |
| 90 |
"Warning issued on line `{line}` of code block {filename}." |
| 91 |
).format(filename=short_filename, line=self.lineno) |
| 92 |
else: |
| 93 |
location = _( |
| 94 |
"Warning issued on line `{line}` of file '{filename}'." |
| 95 |
).format(filename=short_filename, line=self.lineno) |
| 96 |
self.info["warning_location_header"] = location + "\n" |
| 97 |
|
| 98 |
self.info.update(**get_warning_cause(self.warning_type, self.message, self)) |
| 99 |
|
| 100 |
def format_source(self): |
| 101 |
nb_digits = len(str(self.lineno)) |
| 102 |
lineno_fmt_string = "{:%d}| " % nb_digits |
| 103 |
line_gap_string = " " * nb_digits + "(...)" |
| 104 |
line_number_gap_string = " " * (nb_digits - 1) + ":" |
| 105 |
|
| 106 |
formatter = FriendlyFormatter( |
| 107 |
options=Options(blank_lines=BlankLines.SINGLE, before=2), |
| 108 |
line_number_format_string=lineno_fmt_string, |
| 109 |
line_gap_string=line_gap_string, |
| 110 |
line_number_gap_string=line_number_gap_string, |
| 111 |
) |
| 112 |
formatted = formatter.format_frame(self.frame) |
| 113 |
return "".join(list(formatted)[1:]) |
| 114 |
|
| 115 |
def get_source_frame_missing(self): |
| 116 |
new_lines = [] |
| 117 |
try: |
| 118 |
source = executing.Source.for_filename(self.filename) |
| 119 |
statement = source.statements_at_line(self.lineno).pop() |
| 120 |
lines = source.lines[statement.lineno - 1 : statement.end_lineno] |
| 121 |
for number, line in enumerate(lines, start=statement.lineno): |
| 122 |
if number == self.lineno: |
| 123 |
new_lines.append(f" -->{number}| {line}") |
| 124 |
else: |
| 125 |
new_lines.append(f" {number}| {line}") |
| 126 |
self.problem_statement = "".join(lines) |
| 127 |
return "\n".join(new_lines) |
| 128 |
except Exception: |
| 129 |
self.problem_statement = None |
| 130 |
|
| 131 |
|
| 132 |
self.problem_statement = "".join( |
| 133 |
self.lines if self.lines is not None else [] |
| 134 |
) |
| 135 |
return ( |
| 136 |
f" -->{self.lineno}| {self.problem_statement}" |
| 137 |
if self.problem_statement |
| 138 |
else _( |
| 139 |
"The source is unavailable.\n" |
| 140 |
"If you used `exec`, consider using `friendly_exec` instead." |
| 141 |
) |
| 142 |
) |
| 143 |
|
| 144 |
|
| 145 |
def saw_warning_before(warning_type, message, filename, lineno) -> bool: |
| 146 |
"""Records a warning if it has not been seen at the exact location |
| 147 |
and returns True; returns False otherwise. |
| 148 |
""" |
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
if warning_type in _warnings_seen: |
| 153 |
if message in _warnings_seen[warning_type]: |
| 154 |
if filename in _warnings_seen[warning_type][message]: |
| 155 |
if lineno in _warnings_seen[warning_type][message][filename]: |
| 156 |
return True |
| 157 |
_warnings_seen[warning_type][message][filename].append(lineno) |
| 158 |
else: |
| 159 |
_warnings_seen[warning_type][message][filename] = [lineno] |
| 160 |
else: |
| 161 |
_warnings_seen[warning_type][message] = {filename: [lineno]} |
| 162 |
else: |
| 163 |
_warnings_seen[warning_type] = {message: {}} |
| 164 |
_warnings_seen[warning_type][message][filename] = [lineno] |
| 165 |
return False |
| 166 |
|
| 167 |
|
| 168 |
def show_warning( |
| 169 |
warning_instance, warning_type, filename, lineno, file=None, line=None |
| 170 |
): |
| 171 |
for do_not_show_warning in IGNORE_WARNINGS: |
| 172 |
if do_not_show_warning(warning_instance, warning_type, filename, lineno): |
| 173 |
return |
| 174 |
|
| 175 |
if saw_warning_before( |
| 176 |
warning_type.__name__, str(warning_instance), filename, lineno |
| 177 |
): |
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
return |
| 182 |
|
| 183 |
try: |
| 184 |
for outer_frame in inspect.getouterframes(inspect.currentframe()): |
| 185 |
if outer_frame.filename == filename and outer_frame.lineno == lineno: |
| 186 |
warning_data = WarningInfo( |
| 187 |
warning_instance, |
| 188 |
warning_type, |
| 189 |
filename, |
| 190 |
lineno, |
| 191 |
frame=outer_frame.frame, |
| 192 |
lines=outer_frame.code_context, |
| 193 |
) |
| 194 |
break |
| 195 |
else: |
| 196 |
warning_data = WarningInfo(warning_instance, warning_type, filename, lineno) |
| 197 |
except Exception: |
| 198 |
warning_data = WarningInfo(warning_instance, warning_type, filename, lineno) |
| 199 |
|
| 200 |
message = str(warning_instance) |
| 201 |
|
| 202 |
if not _RUNNING_TESTS: |
| 203 |
session.recorded_tracebacks.append(warning_data) |
| 204 |
elif "cause" in warning_data.info: |
| 205 |
|
| 206 |
return |
| 207 |
session.write_err(f"`{warning_type.__name__}`: {message}\n") |
| 208 |
|
| 209 |
|
| 210 |
INCLUDED_PARSERS = { |
| 211 |
SyntaxWarning: "syntax_warning", |
| 212 |
} |
| 213 |
WARNING_DATA_PARSERS = {} |
| 214 |
|
| 215 |
|
| 216 |
class WarningDataParser: |
| 217 |
"""This class is used to create objects that collect message parsers.""" |
| 218 |
|
| 219 |
def __init__(self) -> None: |
| 220 |
self.parsers: List[Parser] = [] |
| 221 |
self.core_parsers: List[Parser] = [] |
| 222 |
self.custom_parsers: List[Parser] = [] |
| 223 |
|
| 224 |
def _add(self, func: Parser) -> None: |
| 225 |
"""This method is meant to be used only within friendly-traceback. |
| 226 |
It is used as a decorator to add a message parser to a list that is |
| 227 |
automatically updated. |
| 228 |
""" |
| 229 |
self.parsers.append(func) |
| 230 |
self.core_parsers.append(func) |
| 231 |
|
| 232 |
def add(self, func: Parser) -> None: |
| 233 |
"""This method is meant to be used by projects that extend |
| 234 |
friendly-traceback. It is used as a decorator to add a message parser |
| 235 |
to a list that is automatically updated:: |
| 236 |
|
| 237 |
@instance.add |
| 238 |
def some_warning_parsers(message, traceback_data): |
| 239 |
.... |
| 240 |
""" |
| 241 |
self.custom_parsers.append(func) |
| 242 |
self.parsers = self.custom_parsers + self.core_parsers |
| 243 |
|
| 244 |
|
| 245 |
def get_warning_parser(warning_type: Type[_E]) -> WarningDataParser: |
| 246 |
"""Gets a 'parser' to find the cause for a given warning. |
| 247 |
|
| 248 |
Args: |
| 249 |
|
| 250 |
warning_type: a warning class. |
| 251 |
|
| 252 |
Usage:: |
| 253 |
|
| 254 |
parser = get_warning_parser(SomeSpecificWarning) |
| 255 |
|
| 256 |
@parser.add |
| 257 |
def some_meaningful_name(warning_message: str, |
| 258 |
warning_data: WarningDataParser) -> dict: |
| 259 |
if not handled_by_this_function(warning_message): |
| 260 |
return {} # let other parsers deal with it |
| 261 |
|
| 262 |
... |
| 263 |
""" |
| 264 |
if warning_type not in WARNING_DATA_PARSERS: |
| 265 |
WARNING_DATA_PARSERS[warning_type] = WarningDataParser() |
| 266 |
if warning_type in INCLUDED_PARSERS: |
| 267 |
base_path = "friendly_traceback.warning_parsers." |
| 268 |
import_module(base_path + INCLUDED_PARSERS[warning_type]) |
| 269 |
return WARNING_DATA_PARSERS[warning_type] |
| 270 |
|
| 271 |
|
| 272 |
def get_warning_cause( |
| 273 |
warning_type, |
| 274 |
message: str, |
| 275 |
warning_data: WarningDataParser = None, |
| 276 |
) -> CauseInfo: |
| 277 |
"""Attempts to get the likely cause of an exception.""" |
| 278 |
try: |
| 279 |
return get_cause(warning_type, message, warning_data) |
| 280 |
except Exception as e: |
| 281 |
session.write_err("Exception raised") |
| 282 |
session.write_err(str(e)) |
| 283 |
session.write_err(internal_error(e)) |
| 284 |
return {} |
| 285 |
|
| 286 |
|
| 287 |
def get_cause( |
| 288 |
warning_type, |
| 289 |
message: str, |
| 290 |
warning_data: WarningDataParser, |
| 291 |
) -> CauseInfo: |
| 292 |
"""For a given exception type, cycle through the known message parsers, |
| 293 |
looking for one that can find a cause of the exception.""" |
| 294 |
warning_parsers = get_warning_parser(warning_type) |
| 295 |
|
| 296 |
for parser in warning_parsers.parsers: |
| 297 |
|
| 298 |
cause = parser(message, warning_data) |
| 299 |
if cause: |
| 300 |
return cause |
| 301 |
return {} |