Skip to content

Add class decorator #1

@astropenguin

Description

@astropenguin

Add a class decorator for custom DataArray constructor like:

from xarray_custom import coordtype, dataarrayclass

@dataarrayclass(["x", "y"], "custom")
class CustomDataArray:
    meta_0: coordtype(["x"], "int", 0)
    meta_1: coordtype(["y"], "float", 0.0)
    meta_2: coordtype(["x", "y"], "str", "default")

    def double(self):
        return self ** 2

where coordtype is a helper function to create a minimum custom DataArray constructor.

Then the dataarrayclass will automatically create __new__ and other useful class methods like ones and zeros, and a dataarray can be created by the updated class:

da = CustomDataArray([[0, 1], [2, 3]], meta_0=[0, 1], ...)
ones = CustomDataArray.ones([2, 2], meta_0=[0, 1], ...)

The custom methods are removed from the class but can be used through the accessor:

da.custom.double() # ok
da.double() # AttributeError is raised

This is because xarray developers recommend to use an accessor rather than class inheritance.
(See: https://xarray.pydata.org/en/stable/internals.html#extending-xarray)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions