Skip to content

Commit

Permalink
Don't show stdlib paths for user_level_warnings (#8625)
Browse files Browse the repository at this point in the history
Was previously seeing:

```
  <frozen _collections_abc>: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...
  • Loading branch information
max-sixty authored Jan 21, 2024
1 parent f4ed09d commit e4bdc39
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
ValuesView,
)
from enum import Enum
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -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
----------
Expand All @@ -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:
Expand Down

0 comments on commit e4bdc39

Please sign in to comment.