Skip to content

Commit

Permalink
Backport PR pandas-dev#57078: 54628 fix find stack level memory leak
Browse files Browse the repository at this point in the history
  • Loading branch information
mroeschke authored and meeseeksmachine committed Jan 27, 2024
1 parent b445127 commit cae4897
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 10 deletions.
7 changes: 6 additions & 1 deletion pandas/_testing/_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,12 @@ def _assert_raised_with_correct_stacklevel(
frame = inspect.currentframe()
for _ in range(4):
frame = frame.f_back # type: ignore[union-attr]
caller_filename = inspect.getfile(frame) # type: ignore[arg-type]
try:
caller_filename = inspect.getfile(frame) # type: ignore[arg-type]
finally:
# See note in
# https://docs.python.org/3/library/inspect.html#inspect.Traceback
del frame
msg = (
"Warning not set with correct stacklevel. "
f"File where warning is raised: {actual_warning.filename} != "
Expand Down
24 changes: 15 additions & 9 deletions pandas/util/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

if TYPE_CHECKING:
from collections.abc import Generator
from types import FrameType


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

# https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow
frame = inspect.currentframe()
n = 0
while frame:
fname = inspect.getfile(frame)
if fname.startswith(pkg_dir) and not fname.startswith(test_dir):
frame = frame.f_back
n += 1
else:
break
frame: FrameType | None = inspect.currentframe()
try:
n = 0
while frame:
filename = inspect.getfile(frame)
if filename.startswith(pkg_dir) and not filename.startswith(test_dir):
frame = frame.f_back
n += 1
else:
break
finally:
# See note in
# https://docs.python.org/3/library/inspect.html#inspect.Traceback
del frame
return n


Expand Down

0 comments on commit cae4897

Please sign in to comment.