| 1 |
"""Context manager for controlling global state variables.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from abc import ABC |
| 6 |
from abc import abstractmethod |
| 7 |
import contextlib |
| 8 |
from typing import TYPE_CHECKING |
| 9 |
from typing import Generic |
| 10 |
from typing import Literal |
| 11 |
from typing import TypeVar |
| 12 |
from typing import cast |
| 13 |
from typing import final |
| 14 |
from typing import get_args |
| 15 |
from typing import overload |
| 16 |
|
| 17 |
from pyvista import _vtk |
| 18 |
from pyvista.core import _vtk_utilities |
| 19 |
|
| 20 |
if TYPE_CHECKING: |
| 21 |
from typing_extensions import Self |
| 22 |
|
| 23 |
|
| 24 |
T = TypeVar('T') |
| 25 |
|
| 26 |
|
| 27 |
class _StateManager(contextlib.AbstractContextManager[None], ABC, Generic[T]): |
| 28 |
"""Abstract base class for managing a global state variable. |
| 29 |
|
| 30 |
Subclasses must: |
| 31 |
|
| 32 |
- Specify a `Literal` as the subclass' type argument. The literal's |
| 33 |
arguments must specify all allowable options for the state variable. |
| 34 |
- Define a getter and setter for the state. Input validation is not |
| 35 |
required - the input is automatically validated when setting the state. |
| 36 |
|
| 37 |
Examples |
| 38 |
-------- |
| 39 |
>>> from pyvista.core.utilities.state_manager import _StateManager |
| 40 |
>>> from typing import Literal |
| 41 |
|
| 42 |
Define the available options as a ``Literal`` and initialize a global state variable. |
| 43 |
|
| 44 |
>>> _StateOptions = Literal['on', 'off'] |
| 45 |
>>> _GLOBAL_STATE = ['off'] # Init global state. Use list to make it mutable. |
| 46 |
|
| 47 |
Define the class and its state property. |
| 48 |
|
| 49 |
>>> class MyState(_StateManager[_StateOptions]): |
| 50 |
... @property |
| 51 |
... def _state(self) -> _StateOptions: |
| 52 |
... return _GLOBAL_STATE[0] |
| 53 |
... |
| 54 |
... @_state.setter |
| 55 |
... def _state(self, state: _StateOptions) -> None: |
| 56 |
... _GLOBAL_STATE[0] = state |
| 57 |
|
| 58 |
Finally, create an instance of the state manager. |
| 59 |
|
| 60 |
>>> my_state = MyState() |
| 61 |
|
| 62 |
Get the state. |
| 63 |
|
| 64 |
>>> my_state() |
| 65 |
'off' |
| 66 |
|
| 67 |
Set the state. |
| 68 |
|
| 69 |
>>> _ = my_state('on') |
| 70 |
>>> my_state() |
| 71 |
'on' |
| 72 |
|
| 73 |
Use it as a context manager to set the state temporarily: |
| 74 |
|
| 75 |
>>> with my_state('off'): |
| 76 |
... pass |
| 77 |
|
| 78 |
""" |
| 79 |
|
| 80 |
@classmethod |
| 81 |
def _get_state_options_from_literal(cls) -> tuple[str | int | bool]: |
| 82 |
state_manager_fullname = f'{_StateManager.__module__}.{_StateManager.__name__}' |
| 83 |
for base in getattr(cls, '__orig_bases__', ()): |
| 84 |
if str(base).startswith(state_manager_fullname): |
| 85 |
# Get StateManager's typing args |
| 86 |
state_manager_args = get_args(base) |
| 87 |
if len(state_manager_args) == 1: |
| 88 |
# There must only be one arg and it must be a non-empty Literal |
| 89 |
literal = state_manager_args[0] |
| 90 |
if str(literal).startswith('typing.Literal'): |
| 91 |
args = get_args(literal) |
| 92 |
if len(args) >= 1: |
| 93 |
return args |
| 94 |
msg = ( |
| 95 |
'Type argument for subclasses must be a single non-empty Literal with all state ' |
| 96 |
'options provided.' |
| 97 |
) |
| 98 |
raise TypeError(msg) |
| 99 |
|
| 100 |
def __init__(self) -> None: |
| 101 |
"""Initialize context manager.""" |
| 102 |
self._valid_states = self._get_state_options_from_literal() |
| 103 |
self._original_state: T | None = None |
| 104 |
|
| 105 |
@property |
| 106 |
@abstractmethod |
| 107 |
def _state(self) -> T: |
| 108 |
"""Get the current global state.""" |
| 109 |
|
| 110 |
@_state.setter |
| 111 |
@abstractmethod |
| 112 |
def _state(self, state: T) -> None: |
| 113 |
"""Set the global state.""" |
| 114 |
|
| 115 |
@final |
| 116 |
def _validate_state(self, state: T) -> T: |
| 117 |
from pyvista import _validation # noqa: PLC0415 |
| 118 |
|
| 119 |
_validation.check_contains(self._valid_states, must_contain=state, name='state') |
| 120 |
return state |
| 121 |
|
| 122 |
def __enter__(self) -> None: |
| 123 |
"""Enter context manager.""" |
| 124 |
if self._original_state is None: |
| 125 |
msg = 'State must be set before using it as a context manager.' |
| 126 |
raise ValueError(msg) |
| 127 |
|
| 128 |
def __exit__(self, exc_type, exc_value, traceback): # noqa: ANN001, ANN204 |
| 129 |
"""Exit context manager and restore original state.""" |
| 130 |
self._state = cast('T', self._original_state) |
| 131 |
self._original_state = None # Reset |
| 132 |
|
| 133 |
@overload |
| 134 |
def __call__(self: Self, state: None) -> T: ... |
| 135 |
@overload |
| 136 |
def __call__(self: Self, state: T) -> Self: ... |
| 137 |
def __call__(self: Self, state: T | None = None) -> Self | T: |
| 138 |
"""Call the context manager.""" |
| 139 |
if state is None: |
| 140 |
return self._state |
| 141 |
|
| 142 |
self._validate_state(state) |
| 143 |
|
| 144 |
# Create new instance and store the local state to be restored when exiting |
| 145 |
output = self.__class__() |
| 146 |
output._original_state = self._state |
| 147 |
output._state = state |
| 148 |
return output |
| 149 |
|
| 150 |
|
| 151 |
_VerbosityOptions = Literal[ |
| 152 |
'off', |
| 153 |
'error', |
| 154 |
'warning', |
| 155 |
'info', |
| 156 |
'max', |
| 157 |
] |
| 158 |
|
| 159 |
|
| 160 |
class _VTKVerbosity(_StateManager[_VerbosityOptions]): |
| 161 |
"""Context manager to set VTK verbosity level. |
| 162 |
|
| 163 |
.. versionadded:: 0.45 |
| 164 |
|
| 165 |
Parameters |
| 166 |
---------- |
| 167 |
verbosity : str |
| 168 |
Verbosity of the :vtk:`vtkLogger` to set. |
| 169 |
|
| 170 |
- ``'off'``: No output. |
| 171 |
- ``'error'``: Only error messages. |
| 172 |
- ``'warning'``: Errors and warnings. |
| 173 |
- ``'info'``: Errors, warnings, and info messages. |
| 174 |
- ``'max'``: All messages, including debug info. |
| 175 |
|
| 176 |
Examples |
| 177 |
-------- |
| 178 |
Get the current vtk verbosity. |
| 179 |
|
| 180 |
>>> import pyvista as pv |
| 181 |
>>> pv.vtk_verbosity() |
| 182 |
'info' |
| 183 |
|
| 184 |
Set verbosity to max. |
| 185 |
|
| 186 |
>>> _ = pv.vtk_verbosity('max') |
| 187 |
>>> pv.vtk_verbosity() |
| 188 |
'max' |
| 189 |
|
| 190 |
Create a :func:`~pyvista.Sphere`. Note how many VTK debugging messages are now |
| 191 |
generated as the sphere is created. |
| 192 |
|
| 193 |
>>> mesh = pv.Sphere() |
| 194 |
|
| 195 |
Use it as a context manager to temporarily turn it off. |
| 196 |
|
| 197 |
>>> with pv.vtk_verbosity('off'): |
| 198 |
... mesh = mesh.cell_quality('volume') |
| 199 |
|
| 200 |
The state is restored to its previous value outside the context. |
| 201 |
|
| 202 |
>>> pv.vtk_verbosity() |
| 203 |
'max' |
| 204 |
|
| 205 |
Note that the verbosity state is global and will persist between function |
| 206 |
calls. If the context manager isn't used, the state needs to be reset explicitly. |
| 207 |
Here, we set it back to its default value. |
| 208 |
|
| 209 |
>>> _ = pv.vtk_verbosity('info') |
| 210 |
|
| 211 |
""" |
| 212 |
|
| 213 |
@property |
| 214 |
def _state(self) -> _VerbosityOptions: |
| 215 |
int_to_string: dict[int, _VerbosityOptions] = { |
| 216 |
-9: 'off', |
| 217 |
-2: 'error', |
| 218 |
-1: 'warning', |
| 219 |
0: 'info', |
| 220 |
9: 'max', |
| 221 |
} |
| 222 |
state = _vtk.vtkLogger.GetCurrentVerbosityCutoff() |
| 223 |
try: |
| 224 |
return int_to_string[state] |
| 225 |
except KeyError: |
| 226 |
# Unsupported state, raise error using validation method |
| 227 |
self._validate_state(state) # type: ignore[arg-type] |
| 228 |
msg = 'This line should not be reachable.' # pragma: no cover |
| 229 |
raise RuntimeWarning(msg) # pragma: no cover |
| 230 |
|
| 231 |
@_state.setter |
| 232 |
def _state(self, state: _VerbosityOptions) -> None: |
| 233 |
verbosity_int = _vtk.vtkLogger.ConvertToVerbosity(state.upper()) |
| 234 |
_vtk.vtkLogger.SetStderrVerbosity(verbosity_int) |
| 235 |
|
| 236 |
|
| 237 |
vtk_verbosity = _VTKVerbosity() |
| 238 |
|
| 239 |
|
| 240 |
_VtkSnakeCaseOptions = Literal['allow', 'warning', 'error'] |
| 241 |
|
| 242 |
|
| 243 |
class _vtkSnakeCase(_StateManager[_VtkSnakeCaseOptions]): # noqa: N801 |
| 244 |
"""Context manager to control access to VTK's pythonic snake_case API. |
| 245 |
|
| 246 |
VTK 9.4 introduced pythonic snake_case attributes, e.g. `output_port` instead |
| 247 |
of `GetOutputPort`. These can easily be confused for PyVista attributes |
| 248 |
which also use a snake_case convention. This class controls access to vtk's |
| 249 |
new interface. |
| 250 |
|
| 251 |
.. versionadded:: 0.45 |
| 252 |
|
| 253 |
Parameters |
| 254 |
---------- |
| 255 |
state : 'allow' | 'warning' | 'error' |
| 256 |
Allow or disallow the use of VTK's pythonic snake_case API with |
| 257 |
PyVista-wrapped VTK classes. |
| 258 |
|
| 259 |
- 'allow': Allow accessing VTK-defined snake_case attributes. |
| 260 |
- 'warning': Print a RuntimeWarning when accessing VTK-defined snake_case |
| 261 |
attributes. |
| 262 |
- 'error': Raise a ``PyVistaAttributeError`` when accessing |
| 263 |
VTK-defined snake_case attributes. |
| 264 |
|
| 265 |
Examples |
| 266 |
-------- |
| 267 |
Get the current access state for VTK's snake_case api. |
| 268 |
|
| 269 |
>>> import pyvista as pv |
| 270 |
>>> pv.vtk_snake_case() |
| 271 |
'error' |
| 272 |
|
| 273 |
The following will raise an error because the `information` property is defined |
| 274 |
by :vtk:`vtkDataObject` and is not part of PyVista's API. |
| 275 |
|
| 276 |
>>> # pv.PolyData().information |
| 277 |
|
| 278 |
Allow use of VTK's snake_case attributes. No warning or error is raised. |
| 279 |
|
| 280 |
>>> _ = pv.vtk_snake_case('allow') |
| 281 |
>>> pv.PolyData().information |
| 282 |
<vtkmodules.vtkCommonCore.vtkInformation... |
| 283 |
|
| 284 |
Note that this state is global and will persist between function calls. Set it |
| 285 |
back to its original state explicitly. |
| 286 |
|
| 287 |
>>> _ = pv.vtk_snake_case('error') |
| 288 |
|
| 289 |
Use it as a context manager instead. This way, the state is only temporarily |
| 290 |
modified and is automatically restored. |
| 291 |
|
| 292 |
>>> with pv.vtk_snake_case('allow'): |
| 293 |
... _ = pv.PolyData().information |
| 294 |
|
| 295 |
>>> pv.vtk_snake_case() |
| 296 |
'error' |
| 297 |
|
| 298 |
""" |
| 299 |
|
| 300 |
@property |
| 301 |
def _state(self) -> _VtkSnakeCaseOptions: |
| 302 |
return _vtk_utilities._VTK_SNAKE_CASE_STATE |
| 303 |
|
| 304 |
@_state.setter |
| 305 |
def _state(self, state: _VtkSnakeCaseOptions) -> None: |
| 306 |
_vtk_utilities._VTK_SNAKE_CASE_STATE = state |
| 307 |
|
| 308 |
|
| 309 |
vtk_snake_case = _vtkSnakeCase() |
| 310 |
|
| 311 |
|
| 312 |
_AllowNewAttributesOptions = Literal['private', True, False] |
| 313 |
|
| 314 |
|
| 315 |
class _AllowNewAttributes(_StateManager[_AllowNewAttributesOptions]): |
| 316 |
"""Context manager to control setting new attributes on PyVista classes. |
| 317 |
|
| 318 |
Python allows arbitrarily setting new attributes on objects at any time, |
| 319 |
but PyVista's classes do not always allow this. By default, setting a |
| 320 |
new attribute is only allowed when the attribute's name has a leading |
| 321 |
underscore "``_``", i.e. it is a private attribute; attempting to |
| 322 |
set a new public attribute raises an ``AttributeError``. |
| 323 |
|
| 324 |
This context manager may be used to allow or disallow setting `any` new |
| 325 |
attribute, public or private, either globally or within a context. |
| 326 |
|
| 327 |
.. versionadded:: 0.47 |
| 328 |
|
| 329 |
Parameters |
| 330 |
---------- |
| 331 |
mode : 'private' | bool |
| 332 |
Control if setting new attributes is allowed. |
| 333 |
|
| 334 |
- ``'private'``: Allow setting private attributes, but do not allow setting public |
| 335 |
attributes. |
| 336 |
- ``True``: Allow setting any new attribute, either private or public. |
| 337 |
- ``False``: Do not allow setting new attributes, regardless if they are private or public. |
| 338 |
|
| 339 |
``'private'`` is used by default, ``True`` removes all restrictions, and ``False`` |
| 340 |
is most strict. |
| 341 |
|
| 342 |
.. note:: |
| 343 |
|
| 344 |
An attribute is considered private if its name has a leading underscore "``_``". |
| 345 |
|
| 346 |
See Also |
| 347 |
-------- |
| 348 |
pyvista.set_new_attribute |
| 349 |
Function for setting any new attribute on a PyVista object. |
| 350 |
|
| 351 |
Notes |
| 352 |
----- |
| 353 |
Allowing new attributes by default outside ``__init__`` and/or without formally defining |
| 354 |
class properties was found to be a source of bugs for both developers and users of PyVista. |
| 355 |
It's very easy to set the wrong attribute name (e.g. ``interpolate`` vs. ``interpolation``) |
| 356 |
without any errors being generated, and users transitioning from older versions of PyVista |
| 357 |
would have code that sets attributes which were once valid, but have since been deprecated and |
| 358 |
removed. Attempting to set an attribute which is not already defined now raises an |
| 359 |
``AttributeError`` to clearly signal that there is a potential problem with this line of code. |
| 360 |
|
| 361 |
Examples |
| 362 |
-------- |
| 363 |
Get the default attribute mode. |
| 364 |
|
| 365 |
>>> import pyvista as pv |
| 366 |
>>> pv.allow_new_attributes() |
| 367 |
'private' |
| 368 |
|
| 369 |
Setting new `private` attributes on PyVista objects is allowed by default. |
| 370 |
|
| 371 |
>>> mesh = pv.PolyData() |
| 372 |
>>> mesh._foo = 42 # OK |
| 373 |
>>> mesh.foo = 42 # ERROR # doctest: +SKIP |
| 374 |
|
| 375 |
Do not allow setting new attributes. |
| 376 |
|
| 377 |
>>> _ = pv.allow_new_attributes(False) |
| 378 |
>>> mesh._foo = 42 # ERROR # doctest:+SKIP |
| 379 |
>>> mesh.foo = 42 # ERROR # doctest:+SKIP |
| 380 |
|
| 381 |
Note that this state is global and will persist between function calls. Set it |
| 382 |
back to its original state explicitly. |
| 383 |
|
| 384 |
>>> _ = pv.allow_new_attributes('private') |
| 385 |
|
| 386 |
Use it as a context manager instead. This way, the state is only temporarily |
| 387 |
modified and is automatically restored. |
| 388 |
|
| 389 |
>>> with pv.allow_new_attributes(True): |
| 390 |
... mesh._foo = 42 # OK |
| 391 |
... mesh.foo = 42 # OK |
| 392 |
|
| 393 |
>>> pv.allow_new_attributes() |
| 394 |
'private' |
| 395 |
|
| 396 |
""" |
| 397 |
|
| 398 |
@property |
| 399 |
def _state(self) -> _AllowNewAttributesOptions: |
| 400 |
from pyvista import _ALLOW_NEW_ATTRIBUTES_MODE # noqa: PLC0415 |
| 401 |
|
| 402 |
return _ALLOW_NEW_ATTRIBUTES_MODE |
| 403 |
|
| 404 |
@_state.setter |
| 405 |
def _state(self, state: _AllowNewAttributesOptions) -> None: |
| 406 |
import pyvista as pv # noqa: PLC0415 |
| 407 |
|
| 408 |
pv._ALLOW_NEW_ATTRIBUTES_MODE = state |
| 409 |
|
| 410 |
|
| 411 |
allow_new_attributes = _AllowNewAttributes() |