From 358ac84028b73d7f4cea96690f62b75b99e11bda Mon Sep 17 00:00:00 2001 From: jsicard833 Date: Tue, 9 Dec 2025 12:12:42 -0500 Subject: [PATCH] BUG: fix option_context warning stacklevel --- pandas/tests/config/test_config.py | 18 ++++++++++++++++++ pandas/util/_exceptions.py | 7 +++++++ 2 files changed, 25 insertions(+) diff --git a/pandas/tests/config/test_config.py b/pandas/tests/config/test_config.py index 9be1bc5554dc7..fc92f6411de01 100644 --- a/pandas/tests/config/test_config.py +++ b/pandas/tests/config/test_config.py @@ -1,3 +1,6 @@ +import os +import warnings + import pytest from pandas._config import config as cf @@ -477,6 +480,21 @@ def test_option_context_scope(self): # Ensure the current context is reset assert cf.get_option(option_name) == original_value + def test_option_context_deprecated_stacklevel(self): + cf.register_option("a", 1) + cf.deprecate_option("a", FutureWarning) + + expected = os.path.normcase(os.path.abspath(__file__)) + + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always") + with pd.option_context("a", 2): + pass + + assert recorded + for warning in recorded: + assert os.path.normcase(warning.filename) == expected + def test_dictwrapper_getattr(self): options = cf.options # GH 19789 diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py index b3c8e54d3ca7f..9c596a16fc781 100644 --- a/pandas/util/_exceptions.py +++ b/pandas/util/_exceptions.py @@ -44,6 +44,10 @@ def find_stack_level() -> int: pkg_dir = os.path.dirname(pd.__file__) test_dir = os.path.join(pkg_dir, "tests") + contextlib_file = getattr(contextlib, "__file__", None) + contextlib_dir = ( + os.path.dirname(contextlib_file) if contextlib_file is not None else None + ) # https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow frame: FrameType | None = inspect.currentframe() @@ -54,6 +58,9 @@ def find_stack_level() -> int: if filename.startswith(pkg_dir) and not filename.startswith(test_dir): frame = frame.f_back n += 1 + elif contextlib_dir and filename.startswith(contextlib_dir): + frame = frame.f_back + n += 1 else: break finally: