Created
June 28, 2023 17:51
-
-
Save SnoopJ/be1eae680f0a5fa921816be2e96fb45f to your computer and use it in GitHub Desktop.
Demonstration of how Python's error reporting behavior changes when source code is not available
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $ python3 traceback_without_source.py | |
| Executing mod.upper() from in-memory module | |
| Traceback (most recent call last): | |
| File "/tmp/traceback_without_source.py", line 43, in <module> | |
| mod.upper() | |
| File "<unknown>", line 2, in upper | |
| File "<unknown>", line 5, in lower | |
| RuntimeError: Oh no, not again. | |
| --- | |
| Executing mod.upper() from on-disk module | |
| Traceback (most recent call last): | |
| File "/tmp/traceback_without_source.py", line 43, in <module> | |
| mod.upper() | |
| File "/tmp/dummy.py", line 2, in upper | |
| lower() # will this be visible in the traceback? | |
| File "/tmp/dummy.py", line 5, in lower | |
| raise RuntimeError("Oh no, not again.") # will this be visible in the traceback? | |
| RuntimeError: Oh no, not again. | |
| --- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| import traceback | |
| from pathlib import Path | |
| SRC = """\ | |
| def upper(): | |
| lower() # will this be visible in the traceback? | |
| def lower(): | |
| raise RuntimeError("Oh no, not again.") # will this be visible in the traceback? | |
| """ | |
| def make_dummy_module(): | |
| code = compile( | |
| SRC, | |
| "<unknown>", # filename | |
| "exec", # mode | |
| ) | |
| mod = type(sys)("dummy_module") | |
| exec( | |
| code, | |
| mod.__dict__, # globals | |
| mod.__dict__, # locals | |
| ) | |
| return mod | |
| for fn in (None, "dummy.py"): | |
| if fn: | |
| filename = fn or "<unknown>" | |
| Path(fn).write_text(SRC) | |
| import dummy as mod | |
| print(f"Executing mod.upper() from on-disk module") | |
| else: | |
| mod = make_dummy_module() | |
| print(f"Executing mod.upper() from in-memory module") | |
| try: | |
| mod.upper() | |
| except Exception: | |
| traceback.print_exc() | |
| print('\n---\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment