Skip to content

Commit 8288b9b

Browse files
mroeschkelmmx
andauthored
54628 fix find stack level memory leak (#57078)
* fix: prevent potential memory leak * test: unit test to cover find_stack_level utility function * style: linting fixes and forgot to rename a funcdef * style: linter fix and forgot to rename a variable in test * test: simplify test and correct value (direct call stack level is 1 not 0) * Add pydoc reference, remove file * Call finally closer to its use --------- Co-authored-by: Louis Maddox <[email protected]>
1 parent 1fee25c commit 8288b9b

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
@@ -220,7 +220,12 @@ def _assert_raised_with_correct_stacklevel(
220220
frame = inspect.currentframe()
221221
for _ in range(4):
222222
frame = frame.f_back # type: ignore[union-attr]
223-
caller_filename = inspect.getfile(frame) # type: ignore[arg-type]
223+
try:
224+
caller_filename = inspect.getfile(frame) # type: ignore[arg-type]
225+
finally:
226+
# See note in
227+
# https://docs.python.org/3/library/inspect.html#inspect.Traceback
228+
del frame
224229
msg = (
225230
"Warning not set with correct stacklevel. "
226231
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)