It was hard to do because there was no object in the traceback
module, that wasn’t read-only
But I think I made what you want:
import traceback, linecache
code = """
def my_method():
def internal_method():
raise RuntimeError("absxsx")
internal_method()
"""
scope = {}
filename = "<dummy-filename>"
compiled_code = compile(code, filename, "exec")
c_lines = code.splitlines()
exec(compiled_code , scope, scope) # noqa: S102
fun = scope["my_method"]
try:
fun()
except Exception as e:
tb = traceback.TracebackException.from_exception(e)
new_st = list()
for fs in tb.stack:
if fs.filename == filename and len(fs.line) == 0:
if len(c_lines) >= fs.lineno:
fs = traceback.FrameSummary(filename, fs.lineno, fs.name, line=c_lines[fs.lineno-1])
new_st.append(fs)
st = traceback.StackSummary.from_list(new_st)
print("Traceback (most recent call last):")
print(* st.format(), sep="")
print(* tb.format_exception_only(), sep="")
Tell me if it works like You expected