xarray icon indicating copy to clipboard operation
xarray copied to clipboard

get_data or get_varibale method

Open hmaarrfk opened this issue 3 years ago • 3 comments

Is your feature request related to a problem?

I often store a few scalars or arrays in xarray containers.

However, when I want to optionally address their data the code I have to run

import xarray as xr
dataset = xr.Dataset()

my_variable = dataset.get('my_variable', None)
if my_variable is not None:
    my_variable = my_variable.data
else:
    my_variable = np.asarray(1.0)   # the default value I actually want

Describe the solution you'd like

import xarray as xr
dataset = xr.Dataset()

my_variable = dataset.get_data('my_variable', np.asarray(1.0))

Describe alternatives you've considered

No response

Additional context

Thank you!

hmaarrfk avatar Jul 15 '22 20:07 hmaarrfk

I guess the code:

import xarray as xr
dataset = xr.Dataset()

my_variable = np.asarray(dataset.get('my_variable', np.asarray(1.0)))

coerces things as an array.

Talking things out made me find this one. Though it doesn't read very well.

Feel free to close.

hmaarrfk avatar Jul 15 '22 21:07 hmaarrfk

wouldn't you be able to use getattr for that? None does not have a attribute named data, so this should work:

getattr(my_variable, "data", np.asarray(1.0))

keewis avatar Jul 15 '22 21:07 keewis

Interesting.

hmaarrfk avatar Jul 15 '22 23:07 hmaarrfk