# Buggy code
def as_variable(obj, name=None):
    """Convert an object into a Variable.

    Parameters
    ----------
    obj : object
        Object to convert into a Variable.

        - If the object is already a Variable, return a shallow copy.
        - Otherwise, if the object has 'dims' and 'data' attributes, convert
          it into a new Variable.
        - If all else fails, attempt to convert the object into a Variable by
          unpacking it into the arguments for creating a new Variable.
    name : str, optional
        If provided:

        - `obj` can be a 1D array, which is assumed to label coordinate values
          along a dimension of this given name.
        - Variables with name matching one of their dimensions are converted
          into `IndexVariable` objects.

    Returns
    -------
    var : Variable
        The newly created variable.

    """
    # TODO: consider extending this method to automatically handle Iris and
    # pandas objects.
    if hasattr(obj, "variable"):
        # extract the primary Variable from DataArrays
        obj = obj.variable

    if isinstance(obj, Variable):
        obj = obj.copy(deep=False)
    elif hasattr(obj, "dims") and (hasattr(obj, "data") or hasattr(obj, "values")):
        obj_data = getattr(obj, "data", None)
        if obj_data is None:
            obj_data = getattr(obj, "values")
        obj = Variable(
            obj.dims,
            obj_data,
            getattr(obj, "attrs", None),
            getattr(obj, "encoding", None),
        )
    elif isinstance(obj, tuple):
        try:
            obj = Variable(*obj)
        except TypeError:
            # 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)
            )
    elif utils.is_scalar(obj):
        obj = Variable([], obj)
    elif getattr(obj, "name", None) is not None:
        obj = Variable(obj.name, obj)
    elif name is not None:
        data = as_compatible_data(obj)
        if data.ndim != 1:
            raise MissingDimensionsError(
                "cannot set variable %r with %r-dimensional data "
                "without explicit dimension names. Pass a tuple of "
                "(dims, data) instead." % (name, data.ndim)
            )
        obj = Variable(name, obj, fastpath=True)
    else:
        raise TypeError(
            "unable to convert object into a variable without an "
            "explicit list of dimensions: %r" % obj
        )

    if name is not None and name in obj.dims:
        # convert the Variable into an Index
        if obj.ndim != 1:
            raise MissingDimensionsError(
                "%r has more than 1-dimension and the same name as one of its "
                "dimensions %r. xarray disallows such variables because they "
                "conflict with the coordinates used to label "
                "dimensions." % (name, obj.dims)
            )
        obj = obj.to_index_variable()

    return obj


# Traceback (ValueError)
In [1]: import xarray

In [2]: import dask.array as da

In [3]:     coord = da.arange(8, chunks=(4,))
...:     data = da.random.random((8, 8), chunks=(4, 4)) + 1
...:     array = xarray.DataArray(data,
...:                       coords={'x': coord, 'y': coord},
...:                       dims=['x', 'y'])
...:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-b90a33ebf436> in <module>()
3 array = xarray.DataArray(data,
4                   coords={'x': coord, 'y': coord},
----> 5                   dims=['x', 'y'])

/home/mrocklin/workspace/xarray/xarray/core/dataarray.py in __init__(self, data, coords, dims, name, attrs, encoding, fastpath)
227
228             data = as_compatible_data(data)
--> 229             coords, dims = _infer_coords_and_dims(data.shape, coords, dims)
230             variable = Variable(dims, data, attrs, encoding, fastpath=True)
231

/home/mrocklin/workspace/xarray/xarray/core/dataarray.py in _infer_coords_and_dims(shape, coords, dims)
68     if utils.is_dict_like(coords):
69         for k, v in coords.items():
---> 70             new_coords[k] = as_variable(v, name=k)
71     elif coords is not None:
72         for dim, coord in zip(dims, coords):

/home/mrocklin/workspace/xarray/xarray/core/variable.py in as_variable(obj, name)
94                             '{}'.format(obj))
95     elif utils.is_scalar(obj):
---> 96         obj = Variable([], obj)
97     elif getattr(obj, 'name', None) is not None:
98         obj = Variable(obj.name, obj)

/home/mrocklin/workspace/xarray/xarray/core/variable.py in __init__(self, dims, data, attrs, encoding, fastpath)
275         """
276         self._data = as_compatible_data(data, fastpath=fastpath)
--> 277         self._dims = self._parse_dimensions(dims)
278         self._attrs = None
279         self._encoding = None

/home/mrocklin/workspace/xarray/xarray/core/variable.py in _parse_dimensions(self, dims)
439             raise ValueError('dimensions %s must have the same length as the '
440                              'number of data dimensions, ndim=%s'
--> 441                              % (dims, self.ndim))
442         return dims
443

ValueError: dimensions () must have the same length as the number of data dimensions, ndim=1

# Fixed code
def as_variable(obj, name=None):
    """Convert an object into a Variable.

    Parameters
    ----------
    obj : object
        Object to convert into a Variable.

        - If the object is already a Variable, return a shallow copy.
        - Otherwise, if the object has 'dims' and 'data' attributes, convert
          it into a new Variable.
        - If all else fails, attempt to convert the object into a Variable by
          unpacking it into the arguments for creating a new Variable.
    name : str, optional
        If provided:

        - `obj` can be a 1D array, which is assumed to label coordinate values
          along a dimension of this given name.
        - Variables with name matching one of their dimensions are converted
          into `IndexVariable` objects.

    Returns
    -------
    var : Variable
        The newly created variable.

    """
    # TODO: consider extending this method to automatically handle Iris and
    # pandas objects.
    if hasattr(obj, "variable"):
        # extract the primary Variable from DataArrays
        obj = obj.variable

    if isinstance(obj, Variable):
        obj = obj.copy(deep=False)
    elif hasattr(obj, "dims") and (hasattr(obj, "data") or hasattr(obj, "values")):
        obj_data = getattr(obj, "data", None)
        if obj_data is None:
            obj_data = getattr(obj, "values")
        obj = Variable(
            obj.dims,
            obj_data,
            getattr(obj, "attrs", None),
            getattr(obj, "encoding", None),
        )
    elif isinstance(obj, tuple):
        try:
            obj = Variable(*obj)
        except TypeError:
            # 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)
            )
    elif utils.is_scalar(obj):
        obj = Variable([], obj)
    elif isinstance(obj, (pd.Index, IndexVariable)) and obj.name is not None:
        obj = Variable(obj.name, obj)
    elif name is not None:
        data = as_compatible_data(obj)
        if data.ndim != 1:
            raise MissingDimensionsError(
                "cannot set variable %r with %r-dimensional data "
                "without explicit dimension names. Pass a tuple of "
                "(dims, data) instead." % (name, data.ndim)
            )
        obj = Variable(name, obj, fastpath=True)
    else:
        raise TypeError(
            "unable to convert object into a variable without an "
            "explicit list of dimensions: %r" % obj
        )

    if name is not None and name in obj.dims:
        # convert the Variable into an Index
        if obj.ndim != 1:
            raise MissingDimensionsError(
                "%r has more than 1-dimension and the same name as one of its "
                "dimensions %r. xarray disallows such variables because they "
                "conflict with the coordinates used to label "
                "dimensions." % (name, obj.dims)
            )
        obj = obj.to_index_variable()

    return obj