Skip to content

Commit 358ac84

Browse files
committed
BUG: fix option_context warning stacklevel
1 parent 499c5d4 commit 358ac84

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

pandas/tests/config/test_config.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import os
2+
import warnings
3+
14
import pytest
25

36
from pandas._config import config as cf
@@ -477,6 +480,21 @@ def test_option_context_scope(self):
477480
# Ensure the current context is reset
478481
assert cf.get_option(option_name) == original_value
479482

483+
def test_option_context_deprecated_stacklevel(self):
484+
cf.register_option("a", 1)
485+
cf.deprecate_option("a", FutureWarning)
486+
487+
expected = os.path.normcase(os.path.abspath(__file__))
488+
489+
with warnings.catch_warnings(record=True) as recorded:
490+
warnings.simplefilter("always")
491+
with pd.option_context("a", 2):
492+
pass
493+
494+
assert recorded
495+
for warning in recorded:
496+
assert os.path.normcase(warning.filename) == expected
497+
480498
def test_dictwrapper_getattr(self):
481499
options = cf.options
482500
# GH 19789

pandas/util/_exceptions.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ def find_stack_level() -> int:
4444

4545
pkg_dir = os.path.dirname(pd.__file__)
4646
test_dir = os.path.join(pkg_dir, "tests")
47+
contextlib_file = getattr(contextlib, "__file__", None)
48+
contextlib_dir = (
49+
os.path.dirname(contextlib_file) if contextlib_file is not None else None
50+
)
4751

4852
# https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow
4953
frame: FrameType | None = inspect.currentframe()
@@ -54,6 +58,9 @@ def find_stack_level() -> int:
5458
if filename.startswith(pkg_dir) and not filename.startswith(test_dir):
5559
frame = frame.f_back
5660
n += 1
61+
elif contextlib_dir and filename.startswith(contextlib_dir):
62+
frame = frame.f_back
63+
n += 1
5764
else:
5865
break
5966
finally:

0 commit comments

Comments
 (0)