Description
Is it safe to use xarray.core.variable.as_variable()
externally? I guess that currently it is not.
I have a specific use case where this would be very useful.
I'm working on a package that heavily uses and extends xarray for landscape evolution modeling, and inside a custom class for model parameters I want to be able to create xarray.Variable
objects on the fly from any provided object, e.g., a scalar value, an array-like, a (dims, data[, attrs])
tuple, another xarray.Variable
, a xarray.DataArray
... exactly what xarray.core.variable.as_variable()
does.
Although I know that Variable
objects are not needed in most use cases, in this specific case a clean solution would be the following
import xarray as xr
class Parameter(object):
def to_variable(self, obj):
return xr.as_variable(obj)
# ... some validation logic on, e.g., data type, value bounds, dimensions...
# ... add default attributes to the created variable (e.g., units, description...)
I don't think it is a viable option to copy as_variable()
and all its dependent code in my package as it seems to have quite a lot of logic implemented.
A workaround using only public API would be something like:
class Parameter(object):
def to_variable(self, obj):
return xr.Dataset(data_vars={'v': obj}).variables['v']
but it feels a bit hacky.