From 13a183f83d6e0bcdb532dd2e77d0ee6390f653ee Mon Sep 17 00:00:00 2001 From: dcherian Date: Sun, 28 Oct 2018 16:58:32 -0700 Subject: [PATCH] Raise more informative error when converting tuples to Variable. Fixes #1016 --- xarray/core/variable.py | 8 ++++---- xarray/tests/test_dataset.py | 2 +- xarray/tests/test_variable.py | 4 +++- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/xarray/core/variable.py b/xarray/core/variable.py index fefd48b449c..1b503c52e8c 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -76,11 +76,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: diff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py index aa226ff1ce8..a32253c19e5 100644 --- a/xarray/tests/test_dataset.py +++ b/xarray/tests/test_dataset.py @@ -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])}) diff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py index 3753221f352..0bd440781ac 100644 --- a/xarray/tests/test_variable.py +++ b/xarray/tests/test_variable.py @@ -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)