xarray
xarray copied to clipboard
get_data or get_varibale method
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!
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.
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))
Interesting.