Debian Codegraph @

pyvista/plotting/component_registry.py

raw
1 """Registry for plotter components.
2
3 This module implements the namespaced *component* extension point on
4 :class:`pyvista.BasePlotter`. It mirrors the dataset accessor pattern in
5 :mod:`pyvista.core.utilities.accessor_registry` line for line on the
6 registration API and adds two optional lifecycle hooks
7 (``__plotter_close__`` and ``__plotter_deep_clean__``) so plugin authors
8 can release VTK observers, websockets, background threads, and any other
9 state that needs explicit teardown when the plotter shuts down.
10
11 Plugin authors learn one decorator shape and one mental model: the dataset
12 accessor decorator. The component variant adds two optional dunder hooks
13 for cleanup. Everything else aligns.
14
15 Two registration paths are supported:
16
17 1. **Explicit import.** A plugin's module runs the
18 :func:`register_plotter_component` decorator at import time, so any
19 user that does ``import plugin`` gets the component attached.
20 2. **Entry points.** A plugin declares a ``pyvista.plotter_components``
21 entry point in its ``pyproject.toml`` pointing at its component
22 module. PyVista reads the entry-point metadata lazily (no plugin
23 module is imported at ``import pyvista`` time). The plugin module
24 imports only when a user first accesses ``plotter.<name>`` on any
25 plotter and the normal attribute lookup misses.
26
27 See Also
28 --------
29 pyvista.register_plotter_component
30 pyvista.unregister_plotter_component
31 pyvista.registered_plotter_components
32
33 """
34
35 from __future__ import annotations
36
37 import contextlib
38 from importlib import import_module
39 from importlib.metadata import entry_points
40 from typing import TYPE_CHECKING
41 from typing import Any
42 from typing import ClassVar
43 from typing import NamedTuple
44 from typing import Protocol
45 from typing import TypedDict
46 from typing import runtime_checkable
47
48 from pyvista._warn_external import warn_external
49 from pyvista.core.utilities._registry_helpers import handler_source
50
51 if TYPE_CHECKING:
52 from collections.abc import Callable
53
54
55 COMPONENT_ENTRY_POINT_GROUP = 'pyvista.plotter_components'
56
57
58 @runtime_checkable
59 class PlotterComponent(Protocol):
60 """Structural protocol for plotter component classes.
61
62 A component class must accept the plotter instance as its single
63 ``__init__`` argument. Any public methods on the class become
64 available as ``plotter.<namespace>.<method>(...)`` once the class is
65 registered with :func:`~pyvista.register_plotter_component`.
66
67 Two optional dunder hooks participate in the plotter lifecycle and
68 are detected by ``getattr`` at lifecycle time, not by the protocol
69 (since they are optional):
70
71 - ``__plotter_close__(self) -> None`` — called when the plotter
72 closes. Only fires on components that were actually constructed
73 (i.e. accessed at least once). Use this to release VTK observers,
74 close websockets, stop background threads, or otherwise undo any
75 side effects the component is responsible for.
76 - ``__plotter_deep_clean__(self) -> None`` — called from
77 ``BasePlotter.deep_clean``. Optional; if absent, deep
78 clean falls through to the normal close path on the next plotter
79 shutdown.
80
81 .. versionadded:: 0.48.0
82
83 Examples
84 --------
85 Declare a component that satisfies the protocol.
86
87 >>> from pyvista import PlotterComponent
88 >>> class MyComponent:
89 ... def __init__(self, plotter):
90 ... self._plotter = plotter
91 >>> isinstance(MyComponent(None), PlotterComponent)
92 True
93
94 """
95
96 def __init__(self, plotter: Any) -> None: ...
97
98
99 class ComponentRegistration(NamedTuple):
100 """Describe one registered plotter component.
101
102 Returned by :func:`~pyvista.registered_plotter_components`.
103
104 .. versionadded:: 0.48.0
105
106 Attributes
107 ----------
108 name : str
109 The namespace the component is attached under (e.g.
110 ``'scalar_bars'``).
111 target : type
112 The PyVista plotter class (or base class) the component is
113 registered against.
114 component : type
115 The component class itself.
116 source : str
117 Human-readable origin in the form ``'module.qualname'`` for
118 explicit registrations, or the entry-point ``value`` for plugin-
119 discovered ones — useful for debugging which plugin registered
120 a given component.
121
122 """
123
124 name: str
125 target: type
126 component: type
127 source: str
128
129
130 class _ComponentRegistryState(TypedDict):
131 """Stored registry state used for test isolation.
132
133 Records every ``(target_cls, name)`` the registry has touched along
134 with the value that was present on the class dictionary before the
135 component descriptor replaced it (sentinel if the attribute did not
136 exist).
137 """
138
139 registrations: list[ComponentRegistration]
140 prior: dict[tuple[type, str], Any]
141 attached: dict[tuple[type, str], Any]
142 entry_points_loaded: bool
143 pending: dict[str, str]
144
145
146 class _CachedComponent:
147 """Non-data descriptor implementing the lazy-component pattern.
148
149 The first time ``obj.<name>`` is accessed, ``component_cls(obj)`` is
150 constructed and stored in ``obj.__dict__[name]``. The component is
151 also appended to ``obj._components`` for close-time iteration.
152 Subsequent lookups bypass the descriptor and hit ``__dict__``
153 directly because a non-data descriptor yields to instance
154 ``__dict__``.
155
156 The ``obj.__dict__`` write goes through the dictionary directly so
157 it bypasses :class:`pyvista.core.utilities.misc._NoNewAttrMixin`'s
158 ``__setattr__`` freeze without weakening the freeze for any other
159 attribute. When the target class uses ``__slots__`` and no
160 ``__dict__`` is available, the component is constructed fresh on
161 each access — slower but still correct *as long as* the component
162 has no lifecycle hooks. A component that declares
163 ``__plotter_close__`` or ``__plotter_deep_clean__`` cannot be
164 attached to a slots target because there is no stable instance to
165 track for close-time iteration; that combination raises
166 :class:`TypeError` on first access rather than silently leaking
167 whatever the hook was meant to release (VTK observers, websockets,
168 background threads, etc.).
169 """
170
171 _LIFECYCLE_HOOKS: ClassVar[tuple[str, ...]] = (
172 '__plotter_close__',
173 '__plotter_deep_clean__',
174 )
175
176 def __init__(self, name: str, component_cls: type) -> None:
177 self._name = name
178 self._component_cls = component_cls
179
180 def __repr__(self) -> str: # pragma: no cover - trivial
181 return f'<_CachedComponent name={self._name!r} cls={self._component_cls!r}>'
182
183 def __get__(self, obj: Any, objtype: type | None = None) -> Any:
184 if obj is None:
185 return self._component_cls
186 component_instance = self._component_cls(obj)
187 try:
188 obj.__dict__[self._name] = component_instance
189 except AttributeError:
190 # ``__slots__`` target: no ``__dict__`` to cache into and no
191 # stable identity across accesses. Safe to fall through
192 # *only* if the component has no lifecycle hooks — otherwise
193 # the hooks would never fire and any cleanup the component
194 # is responsible for would silently leak.
195 declared = [
196 hook
197 for hook in self._LIFECYCLE_HOOKS
198 if getattr(self._component_cls, hook, None) is not None
199 ]
200 if declared:
201 msg = (
202 f'Plotter component {self._name!r} '
203 f'({self._component_cls.__qualname__}) declares '
204 f'lifecycle hook(s) {declared} but is attached to '
205 f'{type(obj).__qualname__}, which uses ``__slots__`` '
206 'and has no ``__dict__`` to cache the component '
207 "instance in. Lifecycle hooks can't fire on a slots "
208 'target because each attribute access constructs a '
209 'fresh component, so close-time teardown would have '
210 'no stable receiver. Either drop the lifecycle '
211 'hooks or give the target class a ``__dict__`` slot.'
212 )
213 raise TypeError(msg)
214 return component_instance
215 # Track for close / deep-clean iteration. ``_components`` is
216 # initialized on the plotter in ``BasePlotter.__init__``; if a
217 # subclass forgot to chain through, fall back to creating the
218 # list lazily so the descriptor cannot crash bare attribute
219 # access.
220 components = getattr(obj, '_components', None)
221 if components is None:
222 with contextlib.suppress(AttributeError):
223 obj.__dict__['_components'] = []
224 components = obj.__dict__['_components']
225 if components is not None:
226 components.append(component_instance)
227 return component_instance
228
229
230 _MISSING: Any = object()
231
232 _registrations: list[ComponentRegistration] = []
233 _prior_values: dict[tuple[type, str], Any] = {}
234 _entry_points_loaded: bool = False
235 _pending_components: dict[str, str] = {}
236
237
238 def _save_registry_state() -> _ComponentRegistryState:
239 """Snapshot the current registry state for later restoration."""
240 attached: dict[tuple[type, str], Any] = {}
241 for record in _registrations:
242 key = (record.target, record.name)
243 attached[key] = record.target.__dict__.get(record.name, _MISSING)
244 return {
245 'registrations': list(_registrations),
246 'prior': dict(_prior_values),
247 'attached': attached,
248 'entry_points_loaded': _entry_points_loaded,
249 'pending': dict(_pending_components),
250 }
251
252
253 def _restore_registry_state(state: _ComponentRegistryState) -> None:
254 """Restore registry state from a snapshot.
255
256 Removes any components that have been added since the snapshot was
257 taken and re-attaches any that were removed, putting prior built-in
258 attributes back if override had shadowed them.
259 """
260 global _entry_points_loaded # noqa: PLW0603
261 current_keys = {(r.target, r.name) for r in _registrations}
262 snapshot_keys = {(r.target, r.name) for r in state['registrations']}
263
264 for record in _registrations:
265 key = (record.target, record.name)
266 if key in snapshot_keys:
267 continue
268 attr = record.target.__dict__.get(record.name)
269 if isinstance(attr, _CachedComponent):
270 delattr(record.target, record.name)
271 prior = _prior_values.pop(key, _MISSING)
272 if prior is not _MISSING:
273 setattr(record.target, record.name, prior)
274
275 for record in state['registrations']:
276 key = (record.target, record.name)
277 attached_at_snapshot = state['attached'].get(key, _MISSING)
278 if attached_at_snapshot is _MISSING:
279 if record.name in record.target.__dict__:
280 delattr(record.target, record.name)
281 elif (
282 key not in current_keys
283 or record.target.__dict__.get(record.name) is not attached_at_snapshot
284 ):
285 setattr(record.target, record.name, attached_at_snapshot)
286
287 _registrations.clear()
288 _registrations.extend(state['registrations'])
289 _prior_values.clear()
290 _prior_values.update(state['prior'])
291 _entry_points_loaded = state['entry_points_loaded']
292 _pending_components.clear()
293 _pending_components.update(state['pending'])
294
295
296 def _find_component_on_mro(target_cls: type, name: str) -> type | None:
297 """Return the class whose ``__dict__`` owns the component descriptor."""
298 for klass in target_cls.__mro__:
299 attr = klass.__dict__.get(name)
300 if isinstance(attr, _CachedComponent):
301 return klass
302 return None
303
304
305 def _find_shadow_on_mro(target_cls: type, name: str) -> type | None:
306 """Return the class shadowing ``name`` with a non-component attribute.
307
308 Walks ``target_cls.__mro__`` (skipping ``object``) and returns the
309 first class that defines a non-component attribute under ``name``,
310 or ``None`` if none exists. Used to detect built-in attribute
311 shadowing.
312 """
313 for klass in target_cls.__mro__:
314 if klass is object:
315 continue
316 if name not in klass.__dict__:
317 continue
318 attr = klass.__dict__[name]
319 if isinstance(attr, _CachedComponent):
320 return None
321 return klass
322 return None
323
324
325 def _validate_name(name: object) -> str:
326 """Normalize and validate a component name."""
327 if not isinstance(name, str):
328 msg = f'Component name must be a string, got {type(name).__name__}.'
329 raise TypeError(msg)
330 normalized = name.strip()
331 if not normalized:
332 msg = 'Component name must not be empty.'
333 raise ValueError(msg)
334 if normalized.startswith('_'):
335 msg = (
336 f'Component name must not start with an underscore, got {name!r}. '
337 'Leading underscores are reserved for PyVista internals.'
338 )
339 raise ValueError(msg)
340 if not normalized.isidentifier():
341 msg = f'Component name must be a valid Python identifier, got {name!r}.'
342 raise ValueError(msg)
343 return normalized
344
345
346 def _validate_target(target_cls: Any) -> type:
347 """Validate that ``target_cls`` is a class."""
348 if not isinstance(target_cls, type):
349 msg = f'target_cls must be a class, got {type(target_cls).__name__}.'
350 raise TypeError(msg)
351 return target_cls
352
353
354 def register_plotter_component(
355 name: str,
356 target_cls: type | None = None,
357 *,
358 override: bool = False,
359 ) -> Callable[[type], type]:
360 """Register a custom namespaced component on a PyVista plotter class.
361
362 Once registered, the component becomes available as
363 ``plotter.<name>.<method>(...)`` on every instance of ``target_cls``
364 and its subclasses. The component class is instantiated lazily on
365 first access and cached on the plotter instance, so subsequent
366 accesses return the same component object.
367
368 Components participate in the plotter lifecycle: if the class
369 defines ``__plotter_close__`` it is invoked when the plotter
370 closes; if it defines ``__plotter_deep_clean__`` it is invoked from
371 ``BasePlotter.deep_clean``. Both hooks fire only on
372 components that were actually constructed (touched at least once).
373
374 Mirrors :func:`~pyvista.register_dataset_accessor` on the
375 registration surface so plugin authors learn one decorator pattern.
376
377 .. versionadded:: 0.48.0
378
379 Parameters
380 ----------
381 name : str
382 The namespace the component will be attached under. Must be a
383 valid Python identifier that does not start with an underscore.
384
385 target_cls : type, optional
386 The plotter class (or base class) to attach the component to.
387 Defaults to :class:`pyvista.BasePlotter`, which exposes the
388 component on every plotter subclass (including
389 ``pyvistaqt.QtInteractor``).
390
391 override : bool, default: False
392 If ``True``, allow registering a name that shadows an existing
393 built-in attribute on ``target_cls`` (a method, property, or any
394 other non-component attribute). The prior attribute is restored
395 on :func:`~pyvista.unregister_plotter_component`.
396
397 Returns
398 -------
399 callable
400 Decorator that registers the component class passed to it and
401 returns that class unchanged.
402
403 Raises
404 ------
405 ValueError
406 If ``name`` is empty, not a valid identifier, starts with ``_``,
407 or shadows a built-in attribute on ``target_cls`` without
408 ``override=True``.
409
410 TypeError
411 If ``target_cls`` is not a class, or ``name`` is not a string.
412
413 Warns
414 -----
415 UserWarning
416 If ``name`` already refers to a registered component on
417 ``target_cls`` or any ancestor. Pass ``override=True`` to
418 silence the warning when replacement is intentional.
419
420 See Also
421 --------
422 pyvista.unregister_plotter_component
423 pyvista.registered_plotter_components
424 pyvista.PlotterComponent
425
426 Examples
427 --------
428 Register a minimal component on the plotter.
429
430 >>> import pyvista as pv
431 >>> @pv.register_plotter_component('demo')
432 ... class DemoComponent:
433 ... def __init__(self, plotter):
434 ... self._plotter = plotter
435 ...
436 ... def title(self):
437 ... return self._plotter.title
438 >>> pl = pv.Plotter()
439 >>> pl.demo.title() == pl.title
440 True
441
442 Components are cached per plotter. Repeated access returns the same
443 object.
444
445 >>> pl.demo is pl.demo
446 True
447
448 Clean up so the namespace is not visible to later doctest examples.
449
450 >>> pv.unregister_plotter_component('demo')
451 >>> pl.close()
452
453 """
454 normalized = _validate_name(name)
455 target = _resolve_default_target(target_cls)
456
457 def decorator(component_cls: object) -> type:
458 if not isinstance(component_cls, type):
459 msg = f'Component must be a class, got {type(component_cls).__name__}.'
460 raise TypeError(msg)
461 _attach_component(normalized, target, component_cls, override=override)
462 return component_cls
463
464 return decorator
465
466
467 def _resolve_default_target(target_cls: type | None) -> type:
468 """Return the default target class when none is supplied."""
469 if target_cls is None:
470 # Lazy import to avoid a circular dependency at module load.
471 from pyvista.plotting.plotter import BasePlotter # noqa: PLC0415
472
473 return BasePlotter
474 return _validate_target(target_cls)
475
476
477 def _attach_component(
478 name: str,
479 target_cls: type,
480 component_cls: type,
481 *,
482 override: bool,
483 source: str | None = None,
484 ) -> None:
485 """Attach ``component_cls`` as a ``_CachedComponent`` on ``target_cls``."""
486 component_owner = _find_component_on_mro(target_cls, name)
487 if component_owner is not None:
488 if not override:
489 if component_owner is target_cls:
490 location = target_cls.__qualname__
491 else:
492 location = (
493 f'{component_owner.__qualname__} (inherited by {target_cls.__qualname__})'
494 )
495 warn_external(
496 f'Registering plotter component {name!r} on '
497 f'{target_cls.__qualname__} replaces an existing registered '
498 f'component on {location}.',
499 )
500 else:
501 shadow_owner = _find_shadow_on_mro(target_cls, name)
502 if shadow_owner is not None and not override:
503 if shadow_owner is target_cls:
504 location = target_cls.__qualname__
505 else:
506 location = f'{shadow_owner.__qualname__} (inherited by {target_cls.__qualname__})'
507 msg = (
508 f'Cannot register plotter component {name!r} on '
509 f'{target_cls.__qualname__}: shadows built-in attribute on '
510 f'{location}. Pass override=True to force.'
511 )
512 raise ValueError(msg)
513
514 key = (target_cls, name)
515 if key not in _prior_values:
516 _prior_values[key] = target_cls.__dict__.get(name, _MISSING)
517
518 setattr(target_cls, name, _CachedComponent(name, component_cls))
519
520 resolved_source = source if source is not None else handler_source(component_cls)
521 _registrations[:] = [
522 r for r in _registrations if not (r.target is target_cls and r.name == name)
523 ]
524 _registrations.append(
525 ComponentRegistration(
526 name=name,
527 target=target_cls,
528 component=component_cls,
529 source=resolved_source,
530 ),
531 )
532
533
534 def unregister_plotter_component(name: str, target_cls: type | None = None) -> None:
535 """Remove a component previously attached to a plotter class.
536
537 The inverse of :func:`~pyvista.register_plotter_component`. Restores
538 any built-in attribute that was shadowed via ``override=True`` when
539 the component was registered.
540
541 .. versionadded:: 0.48.0
542
543 Parameters
544 ----------
545 name : str
546 Namespace of the component to remove.
547 target_cls : type, optional
548 Target class the component was registered against. Defaults to
549 :class:`pyvista.BasePlotter`. Only components attached directly
550 on ``target_cls`` can be unregistered; a component inherited
551 from a parent class must be unregistered on that parent.
552
553 Raises
554 ------
555 ValueError
556 If no component named ``name`` is attached directly to
557 ``target_cls``.
558
559 TypeError
560 If ``target_cls`` is not a class, or ``name`` is not a string.
561
562 Examples
563 --------
564 >>> import pyvista as pv
565 >>> @pv.register_plotter_component('tmp')
566 ... class TmpComponent:
567 ... def __init__(self, plotter):
568 ... self._plotter = plotter
569 >>> pv.unregister_plotter_component('tmp')
570
571 """
572 normalized = _validate_name(name)
573 target = _resolve_default_target(target_cls)
574
575 attr = target.__dict__.get(normalized)
576 if not isinstance(attr, _CachedComponent):
577 msg = (
578 f'No registered plotter component {name!r} attached directly to {target.__qualname__}.'
579 )
580 raise ValueError(msg) # noqa: TRY004
581
582 key = (target, normalized)
583 prior = _prior_values.pop(key, _MISSING)
584 if prior is _MISSING:
585 delattr(target, normalized)
586 else:
587 setattr(target, normalized, prior)
588
589 _registrations[:] = [
590 r for r in _registrations if not (r.target is target and r.name == normalized)
591 ]
592
593
594 def _ensure_entry_points() -> None:
595 """Scan ``pyvista.plotter_components`` entry-point metadata once."""
596 global _entry_points_loaded # noqa: PLW0603
597 if _entry_points_loaded:
598 return
599
600 _entry_points_loaded = True
601 for component_entry_point in entry_points(group=COMPONENT_ENTRY_POINT_GROUP):
602 _pending_components[component_entry_point.name] = component_entry_point.value
603
604
605 def _resolve_pending_component(name: str) -> bool:
606 """Import the plugin module registered under ``name``, if any.
607
608 Called from :meth:`pyvista.BasePlotter.__getattr__` when a normal
609 attribute lookup misses. Ensures entry-point metadata has been
610 scanned, pops the pending entry for ``name``, and imports the
611 corresponding plugin module. Importing the module triggers any
612 ``@register_plotter_component`` decorators inside it and attaches
613 the component as a side effect.
614
615 Returns
616 -------
617 bool
618 ``True`` if a plugin was loaded for ``name`` (and the attribute
619 lookup should be retried). ``False`` if no pending plugin
620 matches ``name``, or if the plugin failed to import.
621
622 """
623 _ensure_entry_points()
624 module_path = _pending_components.pop(name, None)
625 if module_path is None:
626 return False
627 try:
628 import_module(module_path)
629 except Exception as exc: # noqa: BLE001
630 msg = (
631 f'Failed to load {COMPONENT_ENTRY_POINT_GROUP} entry point '
632 f'"{name}" from {module_path}: {exc}'
633 )
634 warn_external(msg)
635 return False
636 return True
637
638
639 def _pending_component_names() -> tuple[str, ...]:
640 """Return every pending component name without importing any plugin."""
641 _ensure_entry_points()
642 return tuple(_pending_components)
643
644
645 def registered_plotter_components() -> tuple[ComponentRegistration, ...]:
646 """Return every plotter component currently registered.
647
648 Forces discovery of any pending entry-point plugins so the returned
649 list reflects every plugin visible to PyVista, not just the ones
650 that have been touched already via attribute access. A plugin that
651 fails to import emits a ``UserWarning`` and is skipped; the rest
652 still appear in the result.
653
654 .. versionadded:: 0.48.0
655
656 Returns
657 -------
658 tuple[ComponentRegistration, ...]
659 Ordered by registration time. Each record exposes ``name``,
660 ``target``, ``component``, and ``source``.
661
662 Examples
663 --------
664 >>> import pyvista as pv
665 >>> @pv.register_plotter_component('demo_listed')
666 ... class DemoListedComponent:
667 ... def __init__(self, plotter):
668 ... self._plotter = plotter
669 >>> [
670 ... r.name
671 ... for r in pv.registered_plotter_components()
672 ... if r.name == 'demo_listed'
673 ... ]
674 ['demo_listed']
675 >>> pv.unregister_plotter_component('demo_listed')
676
677 """
678 _ensure_entry_points()
679 for pending_name in list(_pending_components):
680 _resolve_pending_component(pending_name)
681 return tuple(_registrations)