| 1 |
"""Global configuration for PyVista core (non-plotting) behavior. |
| 2 |
|
| 3 |
This module exposes :data:`pyvista.global_config`, a singleton :class:`Config` |
| 4 |
instance that holds process-wide settings for the ``pyvista.core`` layer. It is |
| 5 |
a sibling to :data:`pyvista.global_theme` (defined in |
| 6 |
:mod:`pyvista.plotting.themes`) and shares the same machinery: both inherit |
| 7 |
from :class:`_ConfigBase` and behave the same way for attribute access, |
| 8 |
dict-style item access, ``to_dict`` / ``from_dict`` serialization, and equality |
| 9 |
comparison. |
| 10 |
|
| 11 |
The base class lives here in :mod:`pyvista.core` rather than in |
| 12 |
:mod:`pyvista.plotting` so that the core layer does not depend on plotting. |
| 13 |
:mod:`pyvista.plotting.themes` imports :class:`_ConfigBase` from here to build |
| 14 |
the plotting theme hierarchy. |
| 15 |
|
| 16 |
To add a new core setting: |
| 17 |
|
| 18 |
1. Add an underscore-prefixed slot to ``Config.__slots__``. |
| 19 |
2. Initialize it in :meth:`Config.__init__`. |
| 20 |
3. Expose it via a public ``@property`` getter / setter pair that reads and |
| 21 |
writes the underscore slot. The setter should validate its input. |
| 22 |
|
| 23 |
That is the same pattern used by every theme subclass, so the two hierarchies |
| 24 |
stay symmetrical and ``to_dict`` / ``from_dict`` round-tripping works without |
| 25 |
any extra code. |
| 26 |
|
| 27 |
Examples |
| 28 |
-------- |
| 29 |
Disable the default array-length check that :func:`pyvista.wrap` performs on |
| 30 |
every VTK object it wraps: |
| 31 |
|
| 32 |
>>> import pyvista as pv |
| 33 |
>>> pv.global_config.validate_on_wrap = False |
| 34 |
>>> pv.global_config.validate_on_wrap = True # restore default |
| 35 |
|
| 36 |
Access a setting via dict-style lookup: |
| 37 |
|
| 38 |
>>> pv.global_config['validate_on_wrap'] |
| 39 |
True |
| 40 |
|
| 41 |
Show the VTK-inherited API in :func:`dir` (and IDE tab-completion): |
| 42 |
|
| 43 |
>>> pv.global_config.show_vtk_api = True |
| 44 |
>>> pv.global_config.show_vtk_api = False # restore default |
| 45 |
|
| 46 |
Dump the current config to a plain dict (useful for logging or round-tripping): |
| 47 |
|
| 48 |
>>> pv.global_config.to_dict() |
| 49 |
{'show_vtk_api': False, 'validate_on_wrap': True} |
| 50 |
|
| 51 |
""" |
| 52 |
|
| 53 |
from __future__ import annotations |
| 54 |
|
| 55 |
from itertools import chain |
| 56 |
from typing import TYPE_CHECKING |
| 57 |
from typing import Any |
| 58 |
from typing import ClassVar |
| 59 |
|
| 60 |
if TYPE_CHECKING: |
| 61 |
from typing_extensions import Self |
| 62 |
|
| 63 |
|
| 64 |
# Mostly from https://stackoverflow.com/questions/56579348/how-can-i-force-subclasses-to-have-slots |
| 65 |
class _ForceSlots(type): |
| 66 |
"""Metaclass to force classes and subclasses to have ``__slots__``.""" |
| 67 |
|
| 68 |
@classmethod |
| 69 |
def __prepare__( # type: ignore[override] |
| 70 |
cls, |
| 71 |
name: str, |
| 72 |
bases: tuple[type, ...], |
| 73 |
**kwargs: Any, |
| 74 |
) -> dict[str, Any]: |
| 75 |
super_prepared = super().__prepare__(cls, name, bases, **kwargs) # type: ignore[arg-type, call-arg, misc] |
| 76 |
super_prepared['__slots__'] = () |
| 77 |
return super_prepared # type: ignore[return-value] |
| 78 |
|
| 79 |
|
| 80 |
class _ConfigBase(metaclass=_ForceSlots): |
| 81 |
"""Shared base class for PyVista config objects. |
| 82 |
|
| 83 |
Provides dict-style item access, ``from_dict`` / ``to_dict`` serialization, |
| 84 |
and equality comparison. Used as the base for both the core |
| 85 |
:class:`Config` (this module) and every node of the plotting |
| 86 |
:class:`pyvista.plotting.themes.Theme` hierarchy. |
| 87 |
|
| 88 |
Subclasses must list every attribute as an underscore-prefixed entry in |
| 89 |
their ``__slots__`` and expose each one via a public ``@property`` getter |
| 90 |
/ setter pair that reads and writes the underscore slot. |
| 91 |
|
| 92 |
""" |
| 93 |
|
| 94 |
__slots__: ClassVar[list[str]] = [] |
| 95 |
|
| 96 |
# Slot names (without the leading underscore) that should be omitted from |
| 97 |
# ``to_dict`` output even though they live in ``__slots__``. Subclasses may |
| 98 |
# override this with their own ``frozenset``. |
| 99 |
_TO_DICT_SKIP: ClassVar[frozenset[str]] = frozenset() |
| 100 |
|
| 101 |
@classmethod |
| 102 |
def from_dict(cls, dict_: dict[str, Any]) -> Self: |
| 103 |
"""Create an instance from a dictionary of attribute values. |
| 104 |
|
| 105 |
Parameters |
| 106 |
---------- |
| 107 |
dict_ : dict |
| 108 |
Mapping of public attribute name to value, as produced by |
| 109 |
:meth:`to_dict`. Nested config objects are recursively |
| 110 |
reconstructed via their own ``from_dict``. |
| 111 |
|
| 112 |
Returns |
| 113 |
------- |
| 114 |
Self |
| 115 |
New instance of ``cls`` populated from ``dict_``. |
| 116 |
|
| 117 |
""" |
| 118 |
inst = cls() |
| 119 |
for key, value in dict_.items(): |
| 120 |
attr = getattr(inst, key) |
| 121 |
if hasattr(attr, 'from_dict'): |
| 122 |
setattr(inst, key, attr.from_dict(value)) |
| 123 |
else: |
| 124 |
setattr(inst, key, value) |
| 125 |
return inst |
| 126 |
|
| 127 |
def to_dict(self) -> dict[str, Any]: |
| 128 |
"""Return config parameters as a dictionary. |
| 129 |
|
| 130 |
Returns |
| 131 |
------- |
| 132 |
dict |
| 133 |
Mapping of public attribute name to its current value. Nested |
| 134 |
config objects are recursively serialized via their own |
| 135 |
``to_dict``. Names listed in :attr:`_TO_DICT_SKIP` are omitted. |
| 136 |
|
| 137 |
""" |
| 138 |
skip = type(self)._TO_DICT_SKIP |
| 139 |
dict_: dict[str, Any] = {} |
| 140 |
for key in self._all__slots__(): |
| 141 |
name = key[1:] # strip the leading underscore |
| 142 |
if name in skip: |
| 143 |
continue |
| 144 |
value = getattr(self, key) |
| 145 |
if hasattr(value, 'to_dict'): |
| 146 |
dict_[name] = value.to_dict() |
| 147 |
else: |
| 148 |
dict_[name] = value |
| 149 |
return dict_ |
| 150 |
|
| 151 |
def __eq__(self, other: object) -> bool: |
| 152 |
if not isinstance(other, _ConfigBase): |
| 153 |
return False |
| 154 |
for attr_name in other._all__slots__(): |
| 155 |
attr = getattr(self, attr_name) |
| 156 |
other_attr = getattr(other, attr_name) |
| 157 |
if ( |
| 158 |
isinstance(attr, (tuple, list)) and tuple(attr) != tuple(other_attr) |
| 159 |
) or not attr == other_attr: |
| 160 |
return False |
| 161 |
return True |
| 162 |
|
| 163 |
__hash__ = None # type: ignore[assignment] # https://github.com/pyvista/pyvista/pull/7671 |
| 164 |
|
| 165 |
def __getitem__(self, key: str) -> Any: |
| 166 |
"""Get a value via a key (backwards-compatible dict access).""" |
| 167 |
return getattr(self, key) |
| 168 |
|
| 169 |
def __setitem__(self, key: str, value: Any) -> None: |
| 170 |
"""Set a value via a key (backwards-compatible dict access).""" |
| 171 |
setattr(self, key, value) |
| 172 |
|
| 173 |
@classmethod |
| 174 |
def _all__slots__(cls) -> tuple[str, ...]: |
| 175 |
"""Return all slot names including parent classes.""" |
| 176 |
mro = cls.mro() |
| 177 |
return tuple(chain.from_iterable(c.__slots__ for c in mro if c is not object)) # type: ignore[attr-defined] |
| 178 |
|
| 179 |
|
| 180 |
class Config(_ConfigBase): |
| 181 |
"""PyVista core configuration. |
| 182 |
|
| 183 |
Holds process-wide settings that affect ``pyvista.core`` behavior. The |
| 184 |
singleton instance is exposed as ``pyvista.global_config``. This is the |
| 185 |
sibling of ``pyvista.global_theme`` for plotting (rendering) settings. |
| 186 |
|
| 187 |
Examples |
| 188 |
-------- |
| 189 |
Disable the default array-length check performed by :func:`pyvista.wrap`: |
| 190 |
|
| 191 |
>>> import pyvista as pv |
| 192 |
>>> pv.global_config.validate_on_wrap = False |
| 193 |
>>> pv.global_config.validate_on_wrap = True # restore default |
| 194 |
|
| 195 |
""" |
| 196 |
|
| 197 |
__slots__ = ['_show_vtk_api', '_validate_on_wrap'] |
| 198 |
|
| 199 |
def __init__(self) -> None: |
| 200 |
self._validate_on_wrap: bool = True |
| 201 |
self._show_vtk_api: bool = False |
| 202 |
|
| 203 |
def __repr__(self) -> str: |
| 204 |
header = 'PyVista Config' |
| 205 |
lines = [header, '-' * len(header)] |
| 206 |
lines.extend(f'{key[1:]:<25}: {getattr(self, key)}' for key in self._all__slots__()) |
| 207 |
return '\n'.join(lines) |
| 208 |
|
| 209 |
@property |
| 210 |
def validate_on_wrap(self) -> bool: # numpydoc ignore=RT01 |
| 211 |
"""Return or set whether :func:`pyvista.wrap` validates data arrays. |
| 212 |
|
| 213 |
When ``True`` (the default), :func:`pyvista.wrap` performs a cheap |
| 214 |
array-length sanity check on every VTK object it wraps and emits a |
| 215 |
:class:`~pyvista.InvalidMeshWarning` if any point or cell data array |
| 216 |
has a tuple count that does not match the dataset's point or cell |
| 217 |
count. Set to ``False`` to skip this check globally when the cost |
| 218 |
matters in tight loops and the caller trusts their inputs. |
| 219 |
|
| 220 |
Notes |
| 221 |
----- |
| 222 |
Per-call control is also available via the ``validate`` keyword on |
| 223 |
:func:`pyvista.wrap`, :func:`pyvista.read`, and |
| 224 |
:meth:`pyvista.BaseReader.read`. The per-call keyword takes |
| 225 |
precedence; this global setting is consulted only when the per-call |
| 226 |
keyword is left at its default ``None``. |
| 227 |
|
| 228 |
.. versionadded:: 0.48 |
| 229 |
|
| 230 |
Examples |
| 231 |
-------- |
| 232 |
>>> import pyvista as pv |
| 233 |
>>> pv.global_config.validate_on_wrap |
| 234 |
True |
| 235 |
>>> pv.global_config.validate_on_wrap = False |
| 236 |
>>> pv.global_config.validate_on_wrap = True # restore default |
| 237 |
|
| 238 |
""" |
| 239 |
return self._validate_on_wrap |
| 240 |
|
| 241 |
@validate_on_wrap.setter |
| 242 |
def validate_on_wrap(self, value: bool) -> None: |
| 243 |
# Defensive runtime check for dynamic call sites (e.g. JSON-driven |
| 244 |
# configuration). Static callers are already constrained by the |
| 245 |
# ``bool`` annotation above, so mypy treats the branch below as |
| 246 |
# unreachable. |
| 247 |
if not isinstance(value, bool): |
| 248 |
msg = f'`validate_on_wrap` must be a bool, got {type(value).__name__}.' # type: ignore[unreachable] |
| 249 |
raise TypeError(msg) |
| 250 |
self._validate_on_wrap = value |
| 251 |
|
| 252 |
@property |
| 253 |
def show_vtk_api(self) -> bool: # numpydoc ignore=RT01 |
| 254 |
"""Return or set whether VTK-inherited attributes appear in :func:`dir`. |
| 255 |
|
| 256 |
When ``False`` (the default), attributes inherited from VTK base |
| 257 |
classes are hidden from :func:`dir` and tab-completion on PyVista |
| 258 |
objects that wrap VTK types (data objects, :class:`~pyvista.Renderer`, |
| 259 |
:class:`~pyvista.Actor`, :class:`~pyvista.Property`, etc.). This keeps |
| 260 |
the public surface curated for data-science IDEs such as Positron's |
| 261 |
Variables pane and VS Code's Jupyter extension, and for IPython / |
| 262 |
Jupyter tab-completion. VTK methods remain fully callable regardless |
| 263 |
of this setting. |
| 264 |
|
| 265 |
When ``True``, the full VTK API is enumerated alongside the PyVista |
| 266 |
API, which is useful for VTK developers who want to discover the raw |
| 267 |
VTK method surface via introspection. |
| 268 |
|
| 269 |
.. warning:: |
| 270 |
|
| 271 |
This option requires runtime inspection and does not work with all developer |
| 272 |
tools, e.g. it has no effect when using PyCharm. This is because it relies on |
| 273 |
calling the object's ``__dir__`` method for generating auto-completion |
| 274 |
suggestions. Tools like PyCharm that only use static analysis for |
| 275 |
auto-completion are therefore unaffected. |
| 276 |
|
| 277 |
Notes |
| 278 |
----- |
| 279 |
The snake_case VTK aliases (``number_of_points``, ``deep_copy``, ...) are |
| 280 |
controlled separately by :func:`pyvista.vtk_snake_case`. When |
| 281 |
snake_case is not ``'allow'`` (the default), those names are hidden |
| 282 |
from :func:`dir` regardless of this setting, because accessing them |
| 283 |
would already raise ``PyVistaAttributeError``. |
| 284 |
Enabling snake_case surfaces the snake_case names in :func:`dir`; |
| 285 |
``show_vtk_api`` only controls the CamelCase VTK API. |
| 286 |
|
| 287 |
.. versionadded:: 0.48 |
| 288 |
|
| 289 |
Examples |
| 290 |
-------- |
| 291 |
>>> import pyvista as pv |
| 292 |
>>> pv.global_config.show_vtk_api |
| 293 |
False |
| 294 |
>>> pv.global_config.show_vtk_api = True |
| 295 |
>>> pv.global_config.show_vtk_api = False # restore default |
| 296 |
|
| 297 |
""" |
| 298 |
return self._show_vtk_api |
| 299 |
|
| 300 |
@show_vtk_api.setter |
| 301 |
def show_vtk_api(self, value: bool) -> None: |
| 302 |
if not isinstance(value, bool): |
| 303 |
msg = f'`show_vtk_api` must be a bool, got {type(value).__name__}.' # type: ignore[unreachable] |
| 304 |
raise TypeError(msg) |
| 305 |
self._show_vtk_api = value |
| 306 |
|
| 307 |
|
| 308 |
global_config = Config() |