Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport PR #57078 on branch 2.2.x (54628 fix find stack level memory leak) #57105

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading