Skip to content

Commit 22e384d

Browse files
Backport PR #45247: PERF: find_stack_level (#46881)
Co-authored-by: Thomas Li <[email protected]>
1 parent f7f67ad commit 22e384d

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

pandas/util/_exceptions.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,20 @@ def find_stack_level() -> int:
2929
Find the first place in the stack that is not inside pandas
3030
(tests notwithstanding).
3131
"""
32-
stack = inspect.stack()
3332

3433
import pandas as pd
3534

3635
pkg_dir = os.path.dirname(pd.__file__)
3736
test_dir = os.path.join(pkg_dir, "tests")
3837

39-
for n in range(len(stack)):
40-
fname = stack[n].filename
38+
# https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow
39+
frame = inspect.currentframe()
40+
n = 0
41+
while frame:
42+
fname = inspect.getfile(frame)
4143
if fname.startswith(pkg_dir) and not fname.startswith(test_dir):
42-
continue
44+
frame = frame.f_back
45+
n += 1
4346
else:
4447
break
4548
return n

0 commit comments

Comments
 (0)