Skip to content

Commit f3cbf4c

Browse files
authored
feat(DTO): Populate linecache for generated transfer functions (#4159)
1 parent af1af6b commit f3cbf4c

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

litestar/dto/_codegen_backend.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
from __future__ import annotations
66

7+
import linecache
78
import re
9+
import secrets
810
import textwrap
911
from contextlib import contextmanager, nullcontext
1012
from typing import (
@@ -216,7 +218,20 @@ def _make_function(
216218
"""Wrap the current body contents in a function definition and turn it into a callable object"""
217219
source = f"def {fn_name}({source_value_name}):\n{self._body} return {return_value_name}"
218220
ctx: dict[str, Any] = {**self._fn_locals}
219-
exec(source, ctx) # noqa: S102
221+
222+
# add the function to linecache, to get better stacktraces when an error occurs
223+
# otherwise, the traceback within the generated code will just point
224+
# to '<string>'
225+
file_name = f"dto_transfer_function_{secrets.token_hex(6)}"
226+
linecache.cache[file_name] = (
227+
len(source),
228+
None, # mtime: not applicable
229+
[line + "\n" for line in source.splitlines()],
230+
file_name,
231+
)
232+
code = compile(source, file_name, "exec")
233+
exec(code, ctx) # noqa: S102
234+
220235
return ctx["func"] # type: ignore[no-any-return]
221236

222237
def _add_stmt(self, stmt: str) -> None:

0 commit comments

Comments
 (0)