Skip to content

Commit a744e63

Browse files
Improve non-nanosecond warning (#7238)
* Point to Variable or DataArray constructor in non-nanosecond warning * [test-upstream] Use find_stack_level function from pandas
1 parent 6179d8e commit a744e63

File tree

3 files changed

+94
-3
lines changed

3 files changed

+94
-3
lines changed

xarray/core/utils.py

+78
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,44 @@
11
"""Internal utilities; not for external use"""
2+
# Some functions in this module are derived from functions in pandas. For
3+
# reference, here is a copy of the pandas copyright notice:
4+
5+
# BSD 3-Clause License
6+
7+
# Copyright (c) 2008-2011, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
8+
# All rights reserved.
9+
10+
# Copyright (c) 2011-2022, Open source contributors.
11+
12+
# Redistribution and use in source and binary forms, with or without
13+
# modification, are permitted provided that the following conditions are met:
14+
15+
# * Redistributions of source code must retain the above copyright notice, this
16+
# list of conditions and the following disclaimer.
17+
18+
# * Redistributions in binary form must reproduce the above copyright notice,
19+
# this list of conditions and the following disclaimer in the documentation
20+
# and/or other materials provided with the distribution.
21+
22+
# * Neither the name of the copyright holder nor the names of its
23+
# contributors may be used to endorse or promote products derived from
24+
# this software without specific prior written permission.
25+
26+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
30+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
34+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
236
from __future__ import annotations
337

438
import contextlib
539
import functools
640
import importlib
41+
import inspect
742
import io
843
import itertools
944
import math
@@ -972,3 +1007,46 @@ def module_available(module: str) -> bool:
9721007
Whether the module is installed.
9731008
"""
9741009
return importlib.util.find_spec(module) is not None
1010+
1011+
1012+
def find_stack_level(test_mode=False) -> int:
1013+
"""Find the first place in the stack that is not inside xarray.
1014+
1015+
This is unless the code emanates from a test, in which case we would prefer
1016+
to see the xarray source.
1017+
1018+
This function is taken from pandas.
1019+
1020+
Parameters
1021+
----------
1022+
test_mode : bool
1023+
Flag used for testing purposes to switch off the detection of test
1024+
directories in the stack trace.
1025+
1026+
Returns
1027+
-------
1028+
stacklevel : int
1029+
First level in the stack that is not part of xarray.
1030+
"""
1031+
import xarray as xr
1032+
1033+
pkg_dir = os.path.dirname(xr.__file__)
1034+
test_dir = os.path.join(pkg_dir, "tests")
1035+
1036+
# https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow
1037+
frame = inspect.currentframe()
1038+
n = 0
1039+
while frame:
1040+
fname = inspect.getfile(frame)
1041+
if fname.startswith(pkg_dir) and (not fname.startswith(test_dir) or test_mode):
1042+
frame = frame.f_back
1043+
n += 1
1044+
else:
1045+
break
1046+
return n
1047+
1048+
1049+
def emit_user_level_warning(message, category=None):
1050+
"""Emit a warning at the user level by inspecting the stack trace."""
1051+
stacklevel = find_stack_level()
1052+
warnings.warn(message, category=category, stacklevel=stacklevel)

xarray/core/variable.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@
7171
NON_NANOSECOND_WARNING = (
7272
"Converting non-nanosecond precision {case} values to nanosecond precision. "
7373
"This behavior can eventually be relaxed in xarray, as it is an artifact from "
74-
"pandas which is now beginning to support non-nanosecond precision values."
74+
"pandas which is now beginning to support non-nanosecond precision values. "
75+
"This warning is caused by passing non-nanosecond np.datetime64 or "
76+
"np.timedelta64 values to the DataArray or Variable constructor; it can be "
77+
"silenced by converting the values to nanosecond precision ahead of time."
7578
)
7679

7780

@@ -191,14 +194,14 @@ def _as_nanosecond_precision(data):
191194
isinstance(dtype, pd.DatetimeTZDtype) and dtype.unit != "ns"
192195
)
193196
if non_ns_datetime64 or non_ns_datetime_tz_dtype:
194-
warnings.warn(NON_NANOSECOND_WARNING.format(case="datetime"))
197+
utils.emit_user_level_warning(NON_NANOSECOND_WARNING.format(case="datetime"))
195198
if isinstance(dtype, pd.DatetimeTZDtype):
196199
nanosecond_precision_dtype = pd.DatetimeTZDtype("ns", dtype.tz)
197200
else:
198201
nanosecond_precision_dtype = "datetime64[ns]"
199202
return data.astype(nanosecond_precision_dtype)
200203
elif dtype.kind == "m" and dtype != np.dtype("timedelta64[ns]"):
201-
warnings.warn(NON_NANOSECOND_WARNING.format(case="timedelta"))
204+
utils.emit_user_level_warning(NON_NANOSECOND_WARNING.format(case="timedelta"))
202205
return data.astype("timedelta64[ns]")
203206
else:
204207
return data

xarray/tests/test_utils.py

+10
Original file line numberDiff line numberDiff line change
@@ -266,3 +266,13 @@ def test_infix_dims_errors(supplied, all_):
266266
)
267267
def test_iterate_nested(nested_list, expected):
268268
assert list(iterate_nested(nested_list)) == expected
269+
270+
271+
def test_find_stack_level():
272+
assert utils.find_stack_level() == 1
273+
assert utils.find_stack_level(test_mode=True) == 2
274+
275+
def f():
276+
return utils.find_stack_level(test_mode=True)
277+
278+
assert f() == 3

0 commit comments

Comments
 (0)