Skip to content

Commit 647376d

Browse files
authored
Use variable name in all exceptions raised in as_variable (#7995)
* Use variable name in all exceptions raised in `as_variable` This is more consistent with the other exceptions raised in this function, and helps to more quickly diagnose issues when e.g. creating datasets * Add `as_variable` change to `whats-new`
1 parent 3cdf40d commit 647376d

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

doc/whats-new.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ Documentation
4242
Internal Changes
4343
~~~~~~~~~~~~~~~~
4444

45+
- :py:func:`as_variable` now consistently includes the variable name in any exceptions
46+
raised. (:pull:`7995`). By `Peter Hill <https://github.com/ZedThree>`_
4547

4648
.. _whats-new.2023.07.0:
4749

xarray/core/variable.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -125,17 +125,15 @@ def as_variable(obj, name=None) -> Variable | IndexVariable:
125125
elif isinstance(obj, tuple):
126126
if isinstance(obj[1], DataArray):
127127
raise TypeError(
128-
"Using a DataArray object to construct a variable is"
128+
f"Variable {name!r}: Using a DataArray object to construct a variable is"
129129
" ambiguous, please extract the data using the .data property."
130130
)
131131
try:
132132
obj = Variable(*obj)
133133
except (TypeError, ValueError) as error:
134-
# use .format() instead of % because it handles tuples consistently
135134
raise error.__class__(
136-
"Could not convert tuple of form "
137-
"(dims, data[, attrs, encoding]): "
138-
"{} to Variable.".format(obj)
135+
f"Variable {name!r}: Could not convert tuple of form "
136+
f"(dims, data[, attrs, encoding]): {obj} to Variable."
139137
)
140138
elif utils.is_scalar(obj):
141139
obj = Variable([], obj)
@@ -154,7 +152,7 @@ def as_variable(obj, name=None) -> Variable | IndexVariable:
154152
obj = Variable(name, data, fastpath=True)
155153
else:
156154
raise TypeError(
157-
"unable to convert object into a variable without an "
155+
f"Variable {name!r}: unable to convert object into a variable without an "
158156
f"explicit list of dimensions: {obj!r}"
159157
)
160158

0 commit comments

Comments
 (0)