Skip to content

Instantly share code, notes, and snippets.

@KaoruNishikawa
Last active September 19, 2021 08:08
Show Gist options
  • Select an option

  • Save KaoruNishikawa/cfc6e1eb30e1444fdbcafc7fbd47634e to your computer and use it in GitHub Desktop.

Select an option

Save KaoruNishikawa/cfc6e1eb30e1444fdbcafc7fbd47634e to your computer and use it in GitHub Desktop.
import functools
import types
import xarray as xr
@xr.register_dataarray_accessor("accessor_name")
class Something(xr.DataArray):
__slots__ = (
"_cache",
"_coords",
"_close",
"_indexes",
"_name",
"_variable",
) # Required for subclass of xarray.DataArray.
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.keep_attrs()
@classmethod
def keep_attrs(cls) -> None:
"""Override xarray.DataArray methods to always keep attributes.
Notes
-----
Need to be a classmethod.
"""
exclude = ["__init__"]
parent = cls.__bases__[0]
attrs = parent().__dir__()
for attr in attrs:
if attr in exclude:
continue
try:
attr_obj = getattr(parent, attr)
if isinstance(attr_obj, (types.FunctionType, types.MethodType)):
setattr(cls, attr, cls.with_keep_attrs_True(attr_obj))
except AttributeError:
continue
@staticmethod
def with_keep_attrs_True(func):
"""Make arbitrary function run with context manager."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
with xr.set_options(keep_attrs=True):
return func(*args, **kwargs)
return wrapper
def to_dataarray(self):
return xr.DataArray(self)
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment