Skip to content

Commit

Permalink
Raise more informative error when converting tuples to Variable. (#2523)
Browse files Browse the repository at this point in the history
Fixes #1016
  • Loading branch information
dcherian authored and shoyer committed Oct 31, 2018
1 parent 6d55f99 commit 17815b4
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 6 deletions.
8 changes: 4 additions & 4 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,11 @@ def as_variable(obj, name=None):
elif isinstance(obj, tuple):
try:
obj = Variable(*obj)
except TypeError:
except (TypeError, ValueError) as error:
# use .format() instead of % because it handles tuples consistently
raise TypeError('tuples to convert into variables must be of the '
'form (dims, data[, attrs, encoding]): '
'{}'.format(obj))
raise error.__class__('Could not convert tuple of form '
'(dims, data[, attrs, encoding]): '
'{} to Variable.'.format(obj))
elif utils.is_scalar(obj):
obj = Variable([], obj)
elif isinstance(obj, (pd.Index, IndexVariable)) and obj.name is not None:
Expand Down
2 changes: 1 addition & 1 deletion xarray/tests/test_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def test_constructor(self):
Dataset({'a': x1, 'b': x2})
with raises_regex(ValueError, "disallows such variables"):
Dataset({'a': x1, 'x': z})
with raises_regex(TypeError, 'tuples to convert'):
with raises_regex(TypeError, 'tuple of form'):
Dataset({'x': (1, 2, 3, 4, 5, 6, 7)})
with raises_regex(ValueError, 'already exists as a scalar'):
Dataset({'x': 0, 'y': ('x', [1, 2, 3])})
Expand Down
4 changes: 3 additions & 1 deletion xarray/tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -970,8 +970,10 @@ def test_as_variable(self):
expected_extra.attrs, expected_extra.encoding)
assert_identical(expected_extra, as_variable(xarray_tuple))

with raises_regex(TypeError, 'tuples to convert'):
with raises_regex(TypeError, 'tuple of form'):
as_variable(tuple(data))
with raises_regex(ValueError, 'tuple of form'): # GH1016
as_variable(('five', 'six', 'seven'))
with raises_regex(
TypeError, 'without an explicit list of dimensions'):
as_variable(data)
Expand Down

0 comments on commit 17815b4

Please sign in to comment.