Skip to content

Instantly share code, notes, and snippets.

@SnoopJ
Created June 28, 2023 17:51
Show Gist options
  • Select an option

  • Save SnoopJ/be1eae680f0a5fa921816be2e96fb45f to your computer and use it in GitHub Desktop.

Select an option

Save SnoopJ/be1eae680f0a5fa921816be2e96fb45f to your computer and use it in GitHub Desktop.

Revisions

  1. SnoopJ created this gist Jun 28, 2023.
    22 changes: 22 additions & 0 deletions out.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    $ 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.

    ---
    41 changes: 41 additions & 0 deletions traceback_without_source.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    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')