Skip to content

Commit 1550858

Browse files
Backport PR pandas-dev#57078 on branch 2.2.x (54628 fix find stack level memory leak) (pandas-dev#57105)
Backport PR pandas-dev#57078: 54628 fix find stack level memory leak Co-authored-by: Matthew Roeschke <[email protected]>
1 parent b445127 commit 1550858

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

pandas/_testing/_warnings.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,12 @@ def _assert_raised_with_correct_stacklevel(
218218
frame = inspect.currentframe()
219219
for _ in range(4):
220220
frame = frame.f_back # type: ignore[union-attr]
221-
caller_filename = inspect.getfile(frame) # type: ignore[arg-type]
221+
try:
222+
caller_filename = inspect.getfile(frame) # type: ignore[arg-type]
223+
finally:
224+
# See note in
225+
# https://docs.python.org/3/library/inspect.html#inspect.Traceback
226+
del frame
222227
msg = (
223228
"Warning not set with correct stacklevel. "
224229
f"File where warning is raised: {actual_warning.filename} != "

pandas/util/_exceptions.py

+15-9
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
if TYPE_CHECKING:
1111
from collections.abc import Generator
12+
from types import FrameType
1213

1314

1415
@contextlib.contextmanager
@@ -42,15 +43,20 @@ def find_stack_level() -> int:
4243
test_dir = os.path.join(pkg_dir, "tests")
4344

4445
# https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow
45-
frame = inspect.currentframe()
46-
n = 0
47-
while frame:
48-
fname = inspect.getfile(frame)
49-
if fname.startswith(pkg_dir) and not fname.startswith(test_dir):
50-
frame = frame.f_back
51-
n += 1
52-
else:
53-
break
46+
frame: FrameType | None = inspect.currentframe()
47+
try:
48+
n = 0
49+
while frame:
50+
filename = inspect.getfile(frame)
51+
if filename.startswith(pkg_dir) and not filename.startswith(test_dir):
52+
frame = frame.f_back
53+
n += 1
54+
else:
55+
break
56+
finally:
57+
# See note in
58+
# https://docs.python.org/3/library/inspect.html#inspect.Traceback
59+
del frame
5460
return n
5561

5662

0 commit comments

Comments
 (0)