Skip to content

Commit 17815b4

Browse files
dcherianshoyer
authored andcommitted
Raise more informative error when converting tuples to Variable. (#2523)
Fixes #1016
1 parent 6d55f99 commit 17815b4

File tree

3 files changed

+8
-6
lines changed

3 files changed

+8
-6
lines changed

xarray/core/variable.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,11 @@ def as_variable(obj, name=None):
7777
elif isinstance(obj, tuple):
7878
try:
7979
obj = Variable(*obj)
80-
except TypeError:
80+
except (TypeError, ValueError) as error:
8181
# use .format() instead of % because it handles tuples consistently
82-
raise TypeError('tuples to convert into variables must be of the '
83-
'form (dims, data[, attrs, encoding]): '
84-
'{}'.format(obj))
82+
raise error.__class__('Could not convert tuple of form '
83+
'(dims, data[, attrs, encoding]): '
84+
'{} to Variable.'.format(obj))
8585
elif utils.is_scalar(obj):
8686
obj = Variable([], obj)
8787
elif isinstance(obj, (pd.Index, IndexVariable)) and obj.name is not None:

xarray/tests/test_dataset.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def test_constructor(self):
242242
Dataset({'a': x1, 'b': x2})
243243
with raises_regex(ValueError, "disallows such variables"):
244244
Dataset({'a': x1, 'x': z})
245-
with raises_regex(TypeError, 'tuples to convert'):
245+
with raises_regex(TypeError, 'tuple of form'):
246246
Dataset({'x': (1, 2, 3, 4, 5, 6, 7)})
247247
with raises_regex(ValueError, 'already exists as a scalar'):
248248
Dataset({'x': 0, 'y': ('x', [1, 2, 3])})

xarray/tests/test_variable.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -970,8 +970,10 @@ def test_as_variable(self):
970970
expected_extra.attrs, expected_extra.encoding)
971971
assert_identical(expected_extra, as_variable(xarray_tuple))
972972

973-
with raises_regex(TypeError, 'tuples to convert'):
973+
with raises_regex(TypeError, 'tuple of form'):
974974
as_variable(tuple(data))
975+
with raises_regex(ValueError, 'tuple of form'): # GH1016
976+
as_variable(('five', 'six', 'seven'))
975977
with raises_regex(
976978
TypeError, 'without an explicit list of dimensions'):
977979
as_variable(data)

0 commit comments

Comments
 (0)