register_dataset_accessor

register_dataset_accessor#

register_dataset_accessor(
name: str,
target_cls: type,
*,
override: bool = False,
) Callable[[type], type][source]#

Register a custom namespaced accessor on a PyVista dataset class.

Mirrors the accessor pattern used by pandas and xarray. Once registered, the accessor becomes available as dataset.<name>.<method>(...) on every instance of target_cls and its subclasses. The accessor class is instantiated lazily on first access and cached on the dataset instance, so subsequent accesses return the same accessor object.

Added in version 0.48.0.

Parameters:
namestr

The namespace the accessor will be attached under. Must be a valid Python identifier that does not start with an underscore.

target_clstype

The PyVista dataset class (or base class) to attach the accessor to. Registering against DataSet exposes the accessor on every subclass (PolyData, UnstructuredGrid, ImageData, and so on). Registering against DataObject additionally covers MultiBlock.

overridebool, default: False

If True, allow registering a name that shadows an existing built-in attribute on target_cls (a filter method, property, or any other non-accessor attribute). The prior attribute is restored on unregister_dataset_accessor().

Returns:
callable()

Decorator that registers the accessor class passed to it and returns that class unchanged.

Raises:
ValueError

If name is empty, not a valid identifier, starts with _, or shadows a built-in attribute on target_cls without override=True.

TypeError

If target_cls is not a class, or name is not a string.

Warns:
UserWarning

If name already refers to a registered accessor on target_cls or any ancestor. Emitting a warning rather than raising matches pandas’ behavior and avoids hard-failing when two plugins collide.

Examples

Register a minimal accessor on PolyData.

>>> import pyvista as pv
>>> @pv.register_dataset_accessor('demo', pv.PolyData)
... class DemoAccessor:
...     def __init__(self, mesh):
...         self._mesh = mesh
...
...     def n_points_doubled(self):
...         return self._mesh.n_points * 2
>>> sphere = pv.Sphere()
>>> sphere.demo.n_points_doubled() == sphere.n_points * 2
True

The accessor is cached per instance. Repeated access returns the same object.

>>> sphere.demo is sphere.demo
True

Clean up so the namespace is not visible to later doctest examples.

>>> pv.unregister_dataset_accessor('demo', pv.PolyData)