xarray Internals

xarray builds upon two of the foundational libraries of the scientific Pythonstack, NumPy and pandas. It is written in pure Python (no C or Cythonextensions), which makes it easy to develop and extend. Instead, we pushcompiled code to optional dependencies.

Variable objects

The core internal data structure in xarray is the Variable,which is used as the basic building block behind xarray’sDataset and DataArray types. AVariable consists of:

  • dims: A tuple of dimension names.

  • data: The N-dimensional array (typically, a NumPy or Dask array) storingthe Variable’s data. It must have the same number of dimensions as the lengthof dims.

  • attrs: An ordered dictionary of metadata associated with this array. Byconvention, xarray’s built-in operations never use this metadata.

  • encoding: Another ordered dictionary used to store information about howthese variable’s data is represented on disk. See Reading encoded data for moredetails.

Variable has an interface similar to NumPy arrays, but extended to make useof named dimensions. For example, it uses dim in preference to an axisargument for methods like mean, and supports Broadcasting by dimension name.

However, unlike Dataset and DataArray, the basic Variable does notinclude coordinate labels along each axis.

Variable is public API, but because of its incomplete support for labeleddata, it is mostly intended for advanced uses, such as in xarray itself or forwriting new backends. You can access the variable objects that correspond toxarray objects via the (readonly) Dataset.variables andDataArray.variable attributes.

Extending xarray

xarray is designed as a general purpose library, and hence tries to avoidincluding overly domain specific functionality. But inevitably, the need for moredomain specific logic arises.

One standard solution to this problem is to subclass Dataset and/or DataArray toadd domain specific functionality. However, inheritance is not very robust. It’seasy to inadvertently use internal APIs when subclassing, which means that yourcode may break when xarray upgrades. Furthermore, many builtin methods willonly return native xarray objects.

The standard advice is to use composition over inheritance, butreimplementing an API as large as xarray’s on your own objects can be an oneroustask, even if most methods are only forwarding to xarray implementations.

If you simply want the ability to call a function with the syntax of amethod call, then the builtin pipe() method (copiedfrom pandas) may suffice.

To resolve this issue for more complex cases, xarray has theregister_dataset_accessor() andregister_dataarray_accessor() decorators for adding custom“accessors” on xarray objects. Here’s how you might use these decorators towrite a custom “geo” accessor implementing a geography specific extension toxarray:

  1. import xarray as xr
  2.  
  3.  
  4. @xr.register_dataset_accessor('geo')
  5. class GeoAccessor:
  6. def __init__(self, xarray_obj):
  7. self._obj = xarray_obj
  8. self._center = None
  9.  
  10. @property
  11. def center(self):
  12. """Return the geographic center point of this dataset."""
  13. if self._center is None:
  14. # we can use a cache on our accessor objects, because accessors
  15. # themselves are cached on instances that access them.
  16. lon = self._obj.latitude
  17. lat = self._obj.longitude
  18. self._center = (float(lon.mean()), float(lat.mean()))
  19. return self._center
  20.  
  21. def plot(self):
  22. """Plot data on a map."""
  23. return 'plotting!'

This achieves the same result as if the Dataset class had a cached propertydefined that returns an instance of your class:

  1. class Dataset:
  2. ...
  3. @property
  4. def geo(self)
  5. return GeoAccessor(self)

However, using the register accessor decorators is preferable to simply addingyour own ad-hoc property (i.e., Dataset.geo = property(…)), for severalreasons:

  • It ensures that the name of your property does not accidentally conflict withany other attributes or methods (including other accessors).

  • Instances of accessor object will be cached on the xarray object that createsthem. This means you can save state on them (e.g., to cache computedproperties).

  • Using an accessor provides an implicit namespace for your customfunctionality that clearly identifies it as separate from built-in xarraymethods.

Back in an interactive IPython session, we can use these properties:

  1. In [1]: ds = xr.Dataset({'longitude': np.linspace(0, 10),
  2. ...: 'latitude': np.linspace(0, 20)})
  3. ...:
  4.  
  5. In [2]: ds.geo.center
  6. Out[2]: (10.0, 5.0)
  7.  
  8. In [3]: ds.geo.plot()
  9. Out[3]: 'plotting!'

The intent here is that libraries that extend xarray could add such an accessorto implement subclass specific functionality rather than using actual subclassesor patching in a large number of domain specific methods. For further readingon ways to write new accessors and the philosophy behind the approach, seeGH1080.

To help users keep things straight, please let us know if you plan to write a new accessorfor an open source library. In the future, we will maintain a list of accessorsand the libraries that implement them on this page.