Skip to content

xarray.core.variable.as_variable() part of the public API? #1303

Closed
@benbovy

Description

@benbovy

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions