BasicsΒΆ

A Python class walks into a bar.

[1]:
import numpy as np
from numpy.typing import NDArray
from xattree import xattree, has, dim, array
[2]:
class Foo:
    n: int = dim(default=10)
    a: NDArray[np.float64] = array(default=0., dims=("n",))
[3]:
def bar(cls):
    return cls if has(cls) else xattree(cls)
[4]:
FooBar = bar(Foo)

Note: don’t use the function form, just decorate your classes β€” unless you have good reason, like a joke to make

A short while later it emerges, acting more or less the same, but carrying itself differently β€” more together, somehow.

[5]:
fubar = FooBar()
fubar.a
[5]:
<xarray.DataArray 'a' (n: 10)> Size: 80B
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
Coordinates:
  * n        (n) int64 80B 0 1 2 3 4 5 6 7 8 9

You sense deception. Maybe this is not your typical dive, but one of those places young people go for over-priced caffeine.

A few more, these with strange hats and ominous attributes, stride in. You begin to fret.

[6]:
from xattree import ROOT, field
[7]:
@xattree
class Grid:
    x: int = dim(default=3, scope=ROOT)
    y: int = dim(default=3, scope=ROOT)
[8]:
@xattree
class Arrs:
    a: NDArray[np.float64] = array(default=0.0, dims=("x", "y"))
[9]:
@xattree
class Root:
    grid: Grid = field()
    arrs: Arrs = field()
[10]:
grid = Grid()
root = Root(grid=grid)
arrs = Arrs(parent=root)

Soon something struts out, doing them a perfect imitation. Be not fooled.

[11]:
print(root.data)
<xarray.DataTree 'root'>
Group: /
β”‚   Dimensions:  (x: 3, y: 3)
β”‚   Coordinates:
β”‚     * x        (x) int64 24B 0 1 2
β”‚     * y        (y) int64 24B 0 1 2
β”‚   Attributes:
β”‚       host:      Root(grid=Grid(x=3, y=3, name='grid', strict=True), arrs=Arrs(...
β”‚       metadata:  {'grid': {}, 'arrs': {}, 'x': {}, 'y': {}}
β”œβ”€β”€ Group: /grid
β”‚       Attributes:
β”‚           host:      Grid(x=3, y=3, name='grid', strict=True)
β”‚           metadata:  {'x': {}, 'y': {}}
└── Group: /arrs
        Dimensions:  (x: 3, y: 3)
        Data variables:
            a        (x, y) float64 72B 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
        Attributes:
            host:      Arrs(a=<xarray.DataArray 'a' (x: 3, y: 3)> Size: 72B\narray([[...
            metadata:  {'a': {}}