Skip to content

Commit 19605d7

Browse files
authored
fail-on-template-vars: modernize stack inspection code (#1129)
inspect.stack() returns a list of namedtuple (or retrocompatible objects) since Python 3.5+: let's use the named attribute. cf https://docs.python.org/3/library/inspect.html#inspect.stack And once we have access to a FrameInfo object/namedtuple, access to its frame object and its f_locals member should not need to iterate on all its members: https://docs.python.org/3/reference/datamodel.html#frame-objects
1 parent c746a46 commit 19605d7

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

Diff for: pytest_django/plugin.py

+5-13
Original file line numberDiff line numberDiff line change
@@ -670,13 +670,11 @@ def _get_origin() -> str | None:
670670

671671
# Try to use topmost `self.origin` first (Django 1.9+, and with
672672
# TEMPLATE_DEBUG)..
673-
for f in stack[2:]:
674-
func = f[3]
675-
if func == "render":
676-
frame = f[0]
673+
for frame_info in stack[2:]:
674+
if frame_info.function == "render":
677675
origin: str | None
678676
try:
679-
origin = frame.f_locals["self"].origin
677+
origin = frame_info.frame.f_locals["self"].origin
680678
except (AttributeError, KeyError):
681679
origin = None
682680
if origin is not None:
@@ -686,16 +684,10 @@ def _get_origin() -> str | None:
686684

687685
# finding the ``render`` needle in the stack
688686
frameinfo = reduce(
689-
lambda x, y: y[3] == "render" and "base.py" in y[1] and y or x, stack
687+
lambda x, y: y if y.function == "render" and "base.py" in y.filename else x, stack
690688
)
691-
# assert 0, stack
692-
frame = frameinfo[0]
693-
# finding only the frame locals in all frame members
694-
f_locals = reduce(
695-
lambda x, y: y[0] == "f_locals" and y or x, inspect.getmembers(frame)
696-
)[1]
697689
# ``django.template.base.Template``
698-
template = f_locals["self"]
690+
template = frameinfo.frame.f_locals["self"]
699691
if isinstance(template, Template):
700692
name: str = template.name
701693
return name

0 commit comments

Comments
 (0)