Improve warning stack trace detection

Handle the cases where:
* Several useless "importlib_bootstrap" frames are inserted in between.
* The warning is about syntax, so the file location wouldn't even show up in the stack trace.
This commit is contained in:
Oleh Prypin
2022-09-14 17:51:16 +02:00
parent 62d8a6f44d
commit f0ae255455

View File

@@ -33,7 +33,11 @@ def _showwarning(message, category, filename, lineno, file=None, line=None):
# * Location of call to warn() <-- include this
# * (stdlib) Location of call to showwarning function
# * (this function) Location of call to extract_stack()
stack = traceback.extract_stack()[-4:-2]
stack = [frame for frame in traceback.extract_stack() if frame.line][-4:-2]
# Make sure the actual affected file's name is still present (the case of syntax warning):
if not any(frame.filename == filename for frame in stack):
stack = stack[-1:] + [traceback.FrameSummary(filename, lineno, '')]
tb = ''.join(traceback.format_list(stack))
except Exception:
tb = f' File "{filename}", line {lineno}'