Last active
September 19, 2021 08:08
-
-
Save KaoruNishikawa/cfc6e1eb30e1444fdbcafc7fbd47634e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment