diff --git a/doc/whats-new.rst b/doc/whats-new.rst index 271e4ebdbb4..41dd734cd41 100644 --- a/doc/whats-new.rst +++ b/doc/whats-new.rst @@ -42,6 +42,8 @@ Documentation Internal Changes ~~~~~~~~~~~~~~~~ +- :py:func:`as_variable` now consistently includes the variable name in any exceptions + raised. (:pull:`7995`). By `Peter Hill `_ .. _whats-new.2023.07.0: diff --git a/xarray/core/variable.py b/xarray/core/variable.py index 9271d0c4dbd..d7c927bfd7a 100644 --- a/xarray/core/variable.py +++ b/xarray/core/variable.py @@ -125,17 +125,15 @@ def as_variable(obj, name=None) -> Variable | IndexVariable: elif isinstance(obj, tuple): if isinstance(obj[1], DataArray): raise TypeError( - "Using a DataArray object to construct a variable is" + f"Variable {name!r}: Using a DataArray object to construct a variable is" " ambiguous, please extract the data using the .data property." ) try: obj = Variable(*obj) except (TypeError, ValueError) as error: - # use .format() instead of % because it handles tuples consistently raise error.__class__( - "Could not convert tuple of form " - "(dims, data[, attrs, encoding]): " - "{} to Variable.".format(obj) + f"Variable {name!r}: Could not convert tuple of form " + f"(dims, data[, attrs, encoding]): {obj} to Variable." ) elif utils.is_scalar(obj): obj = Variable([], obj) @@ -154,7 +152,7 @@ def as_variable(obj, name=None) -> Variable | IndexVariable: obj = Variable(name, data, fastpath=True) else: raise TypeError( - "unable to convert object into a variable without an " + f"Variable {name!r}: unable to convert object into a variable without an " f"explicit list of dimensions: {obj!r}" )