| 1 |
"""Pluggable writer registry for custom file formats.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from importlib.metadata import EntryPoint |
| 6 |
from importlib.metadata import entry_points |
| 7 |
from typing import TYPE_CHECKING |
| 8 |
from typing import Any |
| 9 |
from typing import NamedTuple |
| 10 |
from typing import Protocol |
| 11 |
from typing import TypedDict |
| 12 |
from typing import overload |
| 13 |
|
| 14 |
import pyvista as pv |
| 15 |
from pyvista._warn_external import warn_external |
| 16 |
from pyvista.core.utilities._registry_helpers import handler_source |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from collections.abc import Callable |
| 20 |
|
| 21 |
from pyvista.core.dataobject import DataObject |
| 22 |
|
| 23 |
|
| 24 |
class WriterHandler(Protocol): |
| 25 |
"""Callable that writes *dataset* to *path*.""" |
| 26 |
|
| 27 |
def __call__(self, dataset: DataObject, path: str, /, **kwargs: Any) -> None: |
| 28 |
"""Write *dataset* to *path*, consuming format-specific *kwargs*.""" |
| 29 |
|
| 30 |
|
| 31 |
class WriterRegistration(NamedTuple): |
| 32 |
"""Describe one registered custom writer. |
| 33 |
|
| 34 |
Returned by :func:`~pyvista.registered_writers`. |
| 35 |
|
| 36 |
.. versionadded:: 0.48.0 |
| 37 |
|
| 38 |
Attributes |
| 39 |
---------- |
| 40 |
extension : str |
| 41 |
File extension the writer is registered against, including the |
| 42 |
leading dot (e.g. ``'.myformat'``). |
| 43 |
handler : callable |
| 44 |
The writer callable. |
| 45 |
source : str |
| 46 |
Human-readable origin in the form ``'module.qualname'`` for |
| 47 |
explicit registrations or the entry-point ``value`` for |
| 48 |
plugin-discovered registrations. |
| 49 |
|
| 50 |
""" |
| 51 |
|
| 52 |
extension: str |
| 53 |
handler: WriterHandler |
| 54 |
source: str |
| 55 |
|
| 56 |
|
| 57 |
class _RegistryState(TypedDict): |
| 58 |
ext: dict[str, WriterHandler] |
| 59 |
sources: dict[str, str] |
| 60 |
pending: dict[str, list[EntryPoint]] |
| 61 |
entry_points_loaded: bool |
| 62 |
|
| 63 |
|
| 64 |
_custom_ext_writers: dict[str, WriterHandler] = {} |
| 65 |
_custom_ext_writer_sources: dict[str, str] = {} |
| 66 |
# Entry-point metadata, populated by ``_ensure_entry_points``. Maps each |
| 67 |
# extension to the list of ``EntryPoint`` records that declared it. |
| 68 |
# The plugin module itself is *not* imported until that extension is |
| 69 |
# actually requested via :func:`_get_ext_handler`, keeping ``pv.save`` |
| 70 |
# calls for built-in formats free of third-party plugin import cost. |
| 71 |
_pending_ext_writers: dict[str, list[EntryPoint]] = {} |
| 72 |
_entry_points_loaded: bool = False |
| 73 |
_builtin_writer_exts: frozenset[str] | None = None |
| 74 |
|
| 75 |
|
| 76 |
def _save_registry_state() -> _RegistryState: |
| 77 |
"""Snapshot the current registry state for later restoration.""" |
| 78 |
return { |
| 79 |
'ext': _custom_ext_writers.copy(), |
| 80 |
'sources': _custom_ext_writer_sources.copy(), |
| 81 |
'pending': {k: list(v) for k, v in _pending_ext_writers.items()}, |
| 82 |
'entry_points_loaded': _entry_points_loaded, |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
def _restore_registry_state(state: _RegistryState) -> None: |
| 87 |
"""Restore registry state from a snapshot.""" |
| 88 |
global _entry_points_loaded # noqa: PLW0603 |
| 89 |
_custom_ext_writers.clear() |
| 90 |
_custom_ext_writers.update(state['ext']) |
| 91 |
_custom_ext_writer_sources.clear() |
| 92 |
_custom_ext_writer_sources.update(state['sources']) |
| 93 |
_pending_ext_writers.clear() |
| 94 |
_pending_ext_writers.update({k: list(v) for k, v in state['pending'].items()}) |
| 95 |
_entry_points_loaded = state['entry_points_loaded'] |
| 96 |
|
| 97 |
|
| 98 |
def _get_builtin_writer_exts() -> frozenset[str]: |
| 99 |
"""Return the union of file extensions handled by built-in PyVista writers.""" |
| 100 |
global _builtin_writer_exts # noqa: PLW0603 |
| 101 |
if _builtin_writer_exts is not None: |
| 102 |
return _builtin_writer_exts |
| 103 |
|
| 104 |
exts: set[str] = set() |
| 105 |
for cls in ( |
| 106 |
pv.ImageData, |
| 107 |
pv.RectilinearGrid, |
| 108 |
pv.StructuredGrid, |
| 109 |
pv.PolyData, |
| 110 |
pv.UnstructuredGrid, |
| 111 |
pv.ExplicitStructuredGrid, |
| 112 |
pv.PointSet, |
| 113 |
pv.MultiBlock, |
| 114 |
pv.PartitionedDataSet, |
| 115 |
): |
| 116 |
writers = getattr(cls, '_WRITERS', None) or {} |
| 117 |
exts.update(writers.keys()) |
| 118 |
|
| 119 |
_builtin_writer_exts = frozenset(exts) |
| 120 |
return _builtin_writer_exts |
| 121 |
|
| 122 |
|
| 123 |
@overload |
| 124 |
def register_writer( |
| 125 |
key: str, |
| 126 |
handler: None = None, |
| 127 |
*, |
| 128 |
override: bool = False, |
| 129 |
) -> Callable[[WriterHandler], WriterHandler]: ... |
| 130 |
|
| 131 |
|
| 132 |
@overload |
| 133 |
def register_writer( |
| 134 |
key: str, |
| 135 |
handler: WriterHandler, |
| 136 |
*, |
| 137 |
override: bool = False, |
| 138 |
) -> None: ... |
| 139 |
|
| 140 |
|
| 141 |
def register_writer( |
| 142 |
key: str, |
| 143 |
handler: WriterHandler | None = None, |
| 144 |
*, |
| 145 |
override: bool = False, |
| 146 |
) -> Callable[[WriterHandler], WriterHandler] | None: |
| 147 |
"""Register a custom writer for a file extension. |
| 148 |
|
| 149 |
Can be used as a plain call or as a decorator. |
| 150 |
|
| 151 |
.. versionadded:: 0.48.0 |
| 152 |
|
| 153 |
Parameters |
| 154 |
---------- |
| 155 |
key : str |
| 156 |
A file extension (e.g. ``'.myformat'``). |
| 157 |
|
| 158 |
handler : callable, optional |
| 159 |
A callable with signature ``handler(dataset, path, **kwargs)`` that |
| 160 |
writes *dataset* to *path*. Any extra keyword arguments passed to |
| 161 |
:meth:`pyvista.DataObject.save` are forwarded to the handler as |
| 162 |
``**kwargs`` — use them to expose format-specific options such as |
| 163 |
compression level, thread count, or chunking. Handlers that do |
| 164 |
not need per-call options can omit ``**kwargs``; a call to |
| 165 |
:meth:`~pyvista.DataObject.save` that passes extras to such a |
| 166 |
handler will raise :class:`TypeError` from Python itself. When |
| 167 |
``handler`` is omitted the function acts as a decorator and |
| 168 |
returns the decorated callable unchanged. |
| 169 |
|
| 170 |
override : bool, default: False |
| 171 |
If ``True``, allow overriding a built-in PyVista writer for this |
| 172 |
extension and silence the warning that would otherwise fire when |
| 173 |
replacing an existing custom registration. |
| 174 |
|
| 175 |
Returns |
| 176 |
------- |
| 177 |
callable or None |
| 178 |
When used as a decorator (``handler`` omitted), returns the |
| 179 |
decorated function. Otherwise returns ``None``. |
| 180 |
|
| 181 |
Raises |
| 182 |
------ |
| 183 |
ValueError |
| 184 |
If ``key`` collides with a built-in PyVista writer and *override* |
| 185 |
is ``False``. |
| 186 |
|
| 187 |
Warns |
| 188 |
----- |
| 189 |
UserWarning |
| 190 |
If ``key`` already refers to a registered custom writer. The new |
| 191 |
registration replaces the old one (last wins); pass |
| 192 |
``override=True`` to silence the warning. |
| 193 |
|
| 194 |
See Also |
| 195 |
-------- |
| 196 |
pyvista.register_reader |
| 197 |
Sibling API for registering custom readers. |
| 198 |
pyvista.registered_writers |
| 199 |
Introspect every registered writer. |
| 200 |
|
| 201 |
Notes |
| 202 |
----- |
| 203 |
When :meth:`pyvista.DataObject.save` is called, registered custom |
| 204 |
writers are dispatched *before* built-in VTK writers — mirroring |
| 205 |
the dispatch order of :func:`pyvista.read`. Passing |
| 206 |
``override=True`` is therefore the only way to replace a built-in |
| 207 |
writer at save time. |
| 208 |
|
| 209 |
Any keyword arguments passed to :meth:`~pyvista.DataObject.save` |
| 210 |
beyond its documented parameters are forwarded verbatim to the |
| 211 |
registered handler. When no custom writer is registered for the |
| 212 |
target extension, extra keyword arguments raise :class:`TypeError` |
| 213 |
from :meth:`~pyvista.DataObject.save` — PyVista never silently |
| 214 |
drops writer options. |
| 215 |
|
| 216 |
Examples |
| 217 |
-------- |
| 218 |
Register a writer for a custom file extension with a |
| 219 |
format-specific option. |
| 220 |
|
| 221 |
>>> import pyvista as pv |
| 222 |
>>> def my_writer(dataset, path, *, level=3): ... |
| 223 |
>>> pv.register_writer('.myformat', my_writer) # doctest:+SKIP |
| 224 |
>>> pv.Sphere().save('sphere.myformat', level=9) # doctest:+SKIP |
| 225 |
|
| 226 |
Use as a decorator. |
| 227 |
|
| 228 |
>>> @pv.register_writer('.myformat') # doctest:+SKIP |
| 229 |
... def my_writer(dataset, path, **kwargs): ... |
| 230 |
|
| 231 |
""" |
| 232 |
if handler is None: |
| 233 |
# Decorator form: @pv.register_writer('.ext') |
| 234 |
def _decorator(fn: WriterHandler) -> WriterHandler: |
| 235 |
_register(key, fn, override=override) |
| 236 |
return fn |
| 237 |
|
| 238 |
return _decorator |
| 239 |
|
| 240 |
_register(key, handler, override=override) |
| 241 |
return None |
| 242 |
|
| 243 |
|
| 244 |
def _register( |
| 245 |
key: str, |
| 246 |
handler: WriterHandler, |
| 247 |
*, |
| 248 |
override: bool = False, |
| 249 |
source: str | None = None, |
| 250 |
) -> None: |
| 251 |
"""Register a handler in the extension registry.""" |
| 252 |
key = key.lower() |
| 253 |
if not key.startswith('.'): |
| 254 |
key = f'.{key}' |
| 255 |
if not override and key in _get_builtin_writer_exts(): |
| 256 |
msg = ( |
| 257 |
f'Cannot register custom writer for "{key}": ' |
| 258 |
f'collides with a built-in PyVista writer. ' |
| 259 |
f'Use override=True to replace it.' |
| 260 |
) |
| 261 |
raise ValueError(msg) |
| 262 |
if not override and key in _custom_ext_writers: |
| 263 |
existing_source = _custom_ext_writer_sources.get(key, '<unknown>') |
| 264 |
warn_external( |
| 265 |
f'Registering writer for "{key}" replaces an existing custom ' |
| 266 |
f'writer from {existing_source}.', |
| 267 |
) |
| 268 |
_custom_ext_writers[key] = handler |
| 269 |
_custom_ext_writer_sources[key] = source if source is not None else handler_source(handler) |
| 270 |
|
| 271 |
|
| 272 |
def _get_ext_handler(ext: str) -> WriterHandler | None: |
| 273 |
"""Look up a custom extension handler, importing the plugin lazily. |
| 274 |
|
| 275 |
Built-in extensions never trigger entry-point plugin imports — only |
| 276 |
extensions that an installed plugin has actually claimed do. |
| 277 |
""" |
| 278 |
handler = _custom_ext_writers.get(ext) |
| 279 |
if handler is not None: |
| 280 |
return handler |
| 281 |
_ensure_entry_points() |
| 282 |
if ext in _pending_ext_writers: |
| 283 |
_resolve_pending_writer(ext) |
| 284 |
return _custom_ext_writers.get(ext) |
| 285 |
|
| 286 |
|
| 287 |
def _ensure_entry_points() -> None: |
| 288 |
"""Scan ``pyvista.writers`` entry-point metadata once. |
| 289 |
|
| 290 |
Populates :data:`_pending_ext_writers` with every extension declared |
| 291 |
by an installed plugin. The plugin modules themselves are **not** |
| 292 |
imported here; the cost is one ``importlib.metadata.entry_points`` |
| 293 |
call. Plugin imports are deferred to :func:`_resolve_pending_writer`, |
| 294 |
which runs only when a writer for that specific extension is |
| 295 |
actually requested. |
| 296 |
""" |
| 297 |
global _entry_points_loaded # noqa: PLW0603 |
| 298 |
if _entry_points_loaded: |
| 299 |
return |
| 300 |
_entry_points_loaded = True |
| 301 |
|
| 302 |
for ep in entry_points(group='pyvista.writers'): |
| 303 |
key = ep.name.lower() |
| 304 |
if not key.startswith('.'): |
| 305 |
key = f'.{key}' |
| 306 |
if key in _custom_ext_writers: |
| 307 |
continue |
| 308 |
_pending_ext_writers.setdefault(key, []).append(ep) |
| 309 |
|
| 310 |
|
| 311 |
def _resolve_pending_writer(ext: str) -> bool: |
| 312 |
"""Import the plugin claiming *ext*, if any. |
| 313 |
|
| 314 |
Returns |
| 315 |
------- |
| 316 |
bool |
| 317 |
``True`` if a plugin loaded successfully for ``ext``. ``False`` |
| 318 |
if no pending plugin matches, or if the plugin failed to import. |
| 319 |
|
| 320 |
Notes |
| 321 |
----- |
| 322 |
A plugin that fails to import emits a ``UserWarning`` and is dropped |
| 323 |
from the pending list, so subsequent lookups of the same extension |
| 324 |
fall straight through without re-triggering the import or |
| 325 |
re-emitting the warning. |
| 326 |
|
| 327 |
""" |
| 328 |
eps = _pending_ext_writers.pop(ext, None) |
| 329 |
if not eps: |
| 330 |
return False |
| 331 |
winner = eps[0] |
| 332 |
try: |
| 333 |
# ep.load() runs third-party import machinery — it can raise |
| 334 |
# literally anything. Convert to a warning so one broken plugin |
| 335 |
# cannot take down every pyvista.save call. |
| 336 |
handler = winner.load() |
| 337 |
except Exception as err: # noqa: BLE001 |
| 338 |
warn_external( |
| 339 |
f'Failed to load pyvista.writers entry point "{winner.value}" for "{ext}": {err}' |
| 340 |
) |
| 341 |
return False |
| 342 |
_custom_ext_writers[ext] = handler |
| 343 |
_custom_ext_writer_sources[ext] = winner.value |
| 344 |
if len(eps) > 1: |
| 345 |
providers = ', '.join(ep.value for ep in eps) |
| 346 |
warn_external( |
| 347 |
f'Multiple pyvista.writers entry points registered for ' |
| 348 |
f'"{ext}": {providers}. Using {winner.value}.' |
| 349 |
) |
| 350 |
return True |
| 351 |
|
| 352 |
|
| 353 |
def _list_custom_exts() -> list[str]: |
| 354 |
"""Return the list of extensions with registered custom writers. |
| 355 |
|
| 356 |
Triggers lazy entry-point *metadata* discovery so that extensions |
| 357 |
contributed by installed packages appear in error messages listing |
| 358 |
supported formats. The plugin modules themselves are **not** |
| 359 |
imported. |
| 360 |
""" |
| 361 |
_ensure_entry_points() |
| 362 |
return list(_custom_ext_writers.keys() | _pending_ext_writers.keys()) |
| 363 |
|
| 364 |
|
| 365 |
def registered_writers() -> tuple[WriterRegistration, ...]: |
| 366 |
"""Return every custom writer currently registered. |
| 367 |
|
| 368 |
Forces discovery of any pending entry-point plugins so the returned |
| 369 |
list reflects every writer visible to PyVista. A plugin that fails to |
| 370 |
import emits a ``UserWarning`` and is skipped; the rest still appear |
| 371 |
in the result. |
| 372 |
|
| 373 |
.. versionadded:: 0.48.0 |
| 374 |
|
| 375 |
Returns |
| 376 |
------- |
| 377 |
tuple[WriterRegistration, ...] |
| 378 |
One record per registered extension. Each record exposes |
| 379 |
``extension``, ``handler``, and ``source``. |
| 380 |
|
| 381 |
Examples |
| 382 |
-------- |
| 383 |
>>> import pyvista as pv |
| 384 |
>>> def my_writer(dataset, path, **kwargs): ... |
| 385 |
>>> pv.register_writer('.demo_writer', my_writer) |
| 386 |
>>> [ |
| 387 |
... r.extension |
| 388 |
... for r in pv.registered_writers() |
| 389 |
... if r.extension == '.demo_writer' |
| 390 |
... ] |
| 391 |
['.demo_writer'] |
| 392 |
|
| 393 |
""" |
| 394 |
_ensure_entry_points() |
| 395 |
for ext in list(_pending_ext_writers): |
| 396 |
_resolve_pending_writer(ext) |
| 397 |
return tuple( |
| 398 |
WriterRegistration( |
| 399 |
extension=ext, |
| 400 |
handler=handler, |
| 401 |
source=_custom_ext_writer_sources.get(ext, '<unknown>'), |
| 402 |
) |
| 403 |
for ext, handler in _custom_ext_writers.items() |
| 404 |
) |