def find_stack_level(test_mode=False) -> int:
    """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 and modified to exclude standard library paths.

    Parameters
    ----------
    test_mode : bool
        Flag used for testing purposes to switch off the detection of test
        directories in the stack trace.

    Returns
    -------
    stacklevel : int
        First level in the stack that is not part of xarray or the Python standard library.
    """
    import xarray as xr

    pkg_dir = Path(xr.__file__).parent
    test_dir = pkg_dir / "tests"

    std_lib_init = sys.modules["os"].__file__
    # Mostly to appease mypy; I don't think this can happen...
    if std_lib_init is None:
        return 0

    std_lib_dir = Path(std_lib_init).parent

    frame = inspect.currentframe()
    n = 0
    while frame:
        fname = inspect.getfile(frame)
        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:
            break
    return n
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 and modified to exclude standard library paths.

    Parameters
    ----------
    test_mode : bool
        Flag used for testing purposes to switch off the detection of test
        directories in the stack trace.

    Returns
    -------
    stacklevel : int
        First level in the stack that is not part of xarray or the Python standard library.
    
xarray/core/utils.py