From e4bdc3930345eeaa8276bfcbc346ef23607453fd Mon Sep 17 00:00:00 2001 From: Maximilian Roos <5635139+max-sixty@users.noreply.github.com> Date: Sun, 21 Jan 2024 13:08:38 -0800 Subject: [PATCH] Don't show stdlib paths for `user_level_warnings` (#8625) Was previously seeing: ``` :801: FutureWarning: The return type of `Dataset.dims` will be changed to return a set of dimension names in future, in order to be more consistent with `DataArray.dims`. To access a mapping from dimension names to lengths, please use `Dataset.sizes`. ``` Now: ``` /Users/maximilian/workspace/xarray/xarray/tests/test_dataset.py:701: FutureWarning: The return type of `Dataset.dims` will be changed to return a set of dimension names in future, in order to be more consistent with `DataArray.dims`. To access a mapping from dimension names to lengths, please use `Dataset.sizes`. assert ds.dims == ds.sizes ``` It's a heuristic, so not perfect, but I think very likely to be accurate. Any contrary cases very welcome... --- xarray/core/utils.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/xarray/core/utils.py b/xarray/core/utils.py index bf2b2efa13e..3bbf06cf967 100644 --- a/xarray/core/utils.py +++ b/xarray/core/utils.py @@ -60,6 +60,7 @@ ValuesView, ) from enum import Enum +from pathlib import Path from typing import ( TYPE_CHECKING, Any, @@ -1224,12 +1225,12 @@ def module_available(module: str, minversion: str | None = None) -> bool: def find_stack_level(test_mode=False) -> int: - """Find the first place in the stack that is not inside xarray. + """Find the first place in the stack that is not inside xarray or the Python standard library. This is unless the code emanates from a test, in which case we would prefer to see the xarray source. - This function is taken from pandas. + This function is taken from pandas and modified to exclude standard library paths. Parameters ---------- @@ -1240,19 +1241,27 @@ def find_stack_level(test_mode=False) -> int: Returns ------- stacklevel : int - First level in the stack that is not part of xarray. + First level in the stack that is not part of xarray or the Python standard library. """ import xarray as xr - pkg_dir = os.path.dirname(xr.__file__) - test_dir = os.path.join(pkg_dir, "tests") + pkg_dir = Path(xr.__file__).parent + test_dir = pkg_dir / "tests" + + std_lib_dir = Path(sys.modules["os"].__file__).parent # Standard library path - # 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) or test_mode): + if ( + fname.startswith(str(pkg_dir)) + and (not fname.startswith(str(test_dir)) or test_mode) + ) or ( + fname.startswith(str(std_lib_dir)) + and "site-packages" not in fname + and "dist-packages" not in fname + ): frame = frame.f_back n += 1 else: