3 The Python wrappers for VTK are produced algorithmically from the VTK header
4 files, and using VTK through Python is very much like using VTK through C++.
5 Nearly all of the same functionality is available, with Python types converted
6 automatically to C++ types and vice-versa. This document assumes that you
7 are already familiar with VTK itself, and want to know more details about
8 how to use VTK through Python.
11 # Installation {#installation}
13 The most convenient way to install VTK for Python is with pip, which is a
14 package manager that comes with Python:
18 This will provide a basic installation of VTK that includes all core
19 functionality, but which will not include some of the specialized VTK
20 modules that rely on external libraries. Binary packages for VTK can
21 also be downloaded directly from https://www.vtk.org/download/.
23 Instructions for building VTK from source code are given in the file
24 [Documentation/dev/build.md][vtk-build] within the source repository.
26 [vtk-build]: https://gitlab.kitware.com/vtk/vtk/-/blob/release/Documentation/dev/build.md
29 # Importing {#importing}
31 VTK is comprised of over one hundred individual modules. Programs can import
32 just the modules that are needed, in order to reduce load time.
34 from vtkmodules.vtkCommonCore import vtkObject
35 from vtkmodules.vtkFiltersSources import vtkConeSource, vtkSphereSource
36 from vtkmodules.vtkRenderingCore import (
42 import vtkmodules.vtkRenderingOpenGL2
44 When getting started, however, it is hard to know what modules you will need.
45 So if you are experimenting with VTK in a Python console, or writing a quick
46 and dirty Python script, it is easiest to simply import everything. There
47 is a special module called '`all`' that allows this to be done:
49 from vtkmodules.all import *
51 After importing the VTK classes, you can check to see which module each of the
54 for c in vtkObject, vtkConeSource, vtkRenderWindow:
55 print(f"from {c.__module__} import {c.__name__}")
57 The output is as follows:
59 from vtkmodules.vtkCommonCore import vtkObject
60 from vtkmodules.vtkFiltersSources import vtkConeSource
61 from vtkmodules.vtkRenderingCore import vtkRenderWindow
63 ## Factories and Implementation Modules {#implementation-modules}
65 In the first 'import' example above, you might be wondering about this line:
67 import vtkmodules.vtkRenderingOpenGL2
69 This import is needed because `vtkRenderingOpenGL2` provides the OpenGL
70 implementations of the classes in `vtkRenderingCore`. To see this in action,
71 open a new Python console and do the following:
73 >>> from vtkmodules.vtkRenderingCore import vtkRenderWindow
74 >>> renwin = vtkRenderWindow()
76 <class 'vtkmodules.vtkRenderingCore.vtkRenderWindow'>
78 >>> import vtkmodules.vtkRenderingOpenGL2
79 >>> renwin2 = vtkRenderWindow()
81 <class 'vtkmodules.vtkRenderingOpenGL2.vtkXOpenGLRenderWindow'>
83 After `vtkRenderingOpenGL2` has been imported, the `vtkRenderWindow()`
84 constructor magically starts returning a different type of object.
85 This occurs because `vtkRenderWindow` is a *factory* class, which means that
86 the kind of object it produces can be overridden by an *implementation*
87 class. In order for the implementation class to do the override, all that
88 is necessary is that its module is imported. To make things even more
89 confusing, `vtkRenderingOpenGL2` is not the only module that contains
90 implementations for the factory classes in `vtkRenderingCore`. The following
91 modules are often needed, as well:
93 import vtkmodules.vtkInteractionStyle
94 import vtkmodules.vtkRenderingFreeType
96 Although you only need implementations for the factory classes that you use,
97 it can be hard to know which classes are factory classes, or what modules
98 contain implementations for them. Also, it can be difficult to even know
99 what classes you are using, since many VTK classes make use of other VTK
100 classes. An example of this is `vtkDataSetMapper`, which internally uses
101 `vtkPolyDataMapper` to do the rendering. So even though `vtkDataSetMapper` is
102 not a factory class, it needs an OpenGL implmentation for `vtkPolyDataMapper`.
104 The simplest approach is to import all the important implementation modules
105 into your program, even if you are not certain that you need them.
106 * For `vtkRenderingCore`, `import vtkRenderingOpenGL2, vtkRenderingFreeType, vtkInteractionStyle`
107 * For `vtkRenderingVolume`, `import vtkRenderingVolumeOpenGL2`
108 * For `vtkCharts`, `import vtkContextOpenGL2`
110 ## Obsolete VTK Import {#obsolete-import}
112 There are many VTK programs that still use the old '`vtk`' module,
113 instead of using the '`vtkmodules`' package introduced in VTK 8.2:
117 Although this works, it is not recommended. The '`vtk`' module is only for
118 backwards-compatibility and is, in fact, just the '`vtkmodules.all`' with a
119 different name. Because of the details of how the renaming is done, the
120 '`import vtk`' statement can confuse IDEs like PyCharm and make them unable
121 to index the module. Instead, if you desire a module named '`vtk`', either
122 for personal preference or a need for backwards compatibility, then use this:
124 import vtkmodules.all as vtk
126 This will make it clear to people who read your code that '`vtk`' is simply a
127 different name for '`vtkmodules.all`'. It will also keep your IDE from
128 becoming confused about what exactly the '`vtk`' module is.
131 # VTK Classes and Objects {#classes-and-objects}
133 ## Classes Derived from vtkObjectBase {#vtkobject-classes}
135 In C++, classes derived from `vtkObjectBase` are instantiated by calling
136 `New()`. In Python, these classes are instantiated by simply calling the
141 For factory classes, the returned object's type might be a subtype of the
142 class. This occurs because the Python wrappers are actually calling `New()`
143 for you, which allows the VTK factory overrides to occur:
147 <class 'vtkmodules.vtkRenderingOpenGL2.vtkOpenGLActor'>
149 When you create a VTK object in Python, you are in fact creating two
150 objects: a C++ object, and a Python object that holds a pointer to the C++
151 object. The `repr()` of the object shows the memory address of the C++
152 object (in parentheses) and of the Python object (after the '`at`'):
154 >>> a = vtkFloatArray()
156 <vtkmodules.vtkCommonCore.vtkFloatArray(0x5653a6a6f700) at 0x7f0e7aecf5e0>
158 If you call `str()` or `print()` on these objects, the wrappers will call the
159 C++ `PrintSelf()` method. The printed information can be useful for debugging:
163 vtkObject (0x55858308a210)
167 Registered Events: (none)
169 ## Other Classes (Special Types) {#special-types}
171 VTK also uses several classes that aren't derived from `vtkObjectBase`. The
172 most important of these is `vtkVariant`, which can hold any type of object:
174 >>> v1 = vtkVariant('hello')
176 vtkmodules.vtkCommonCore.vtkVariant('hello')
177 >>> v2 = vtkVariant(3.14)
179 vtkmodules.vtkCommonCore.vtkVariant(3.14)
181 The wrapping of these classes is fully automatic, but is done in a slightly
182 different manner than `vtkObjectBase`-derived classes. First, these classes
183 have no `New()` method, and instead the public C++ constructors are wrapped
184 to create an equivalent Python contructor. Second, the Python object
185 contains its own copy of the C++ object, rather than containing just a
186 pointer to the C++ object. The vast majority of these classes are lightweight
187 containers and numerical types. For example, `vtkQuaterniond`, `vtkRectf`,
188 `vtkColor4ub`, etc. Many of them are actually class templates, which are
191 When you apply `print()` or `str()` to these objects, the `operator<<` of the
192 underlying C++ object is used to print them. For `repr()`, the name of the
193 type name is printed, followed by the `str()` output in prentheses. The
194 result looks similar to a constructor, though it might look strange depending
195 on what `operator<<` produces.
199 vtkmodules.vtkCommonCore.vtkVariant((invalid))
201 ## Class Templates {#class-templates}
203 There are several C++ templates in VTK, which can be tricky to use from the
204 wrappers since the Python language has no real concept of templates. The
205 wrappers wrap templates as dictionary-like objects that map the template
206 parameters to template instantiations:
208 >>> vtkSOADataArrayTemplate
209 <template vtkCommonCorePython.vtkSOADataArrayTemplate>
210 >>> vtkSOADataArrayTemplate.keys()
211 ['char', 'int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int',
212 'uint', 'int64', 'uint64', 'float32', 'float64']
213 >>> c = vtkSOADataArrayTemplate['float64']
215 <class 'vtkmodules.vtkCommonCore.vtkSOADataArrayTemplate_IdE'>
217 The wrappers instantiate the C++ template for a few useful types, as
218 indicated by the `keys()` of the template. The Python type name also has a
219 suffix (the '`IdE`') that indicates the template parameters in a compressed
220 form according to IA64 C++ ABI name mangling rules, even when VTK is built
221 with a compiler that does not use the IA64 ABI natively.
223 Objects are created by first instantiating the template, and then
224 instantiating the class:
226 >>> a = vtkSOADataArrayTemplate['float32']()
227 >>> a.SetNumberOfComponents(3)
229 In the case of multiple template parameters, the syntax can look rather
230 complicated, but really it isn't all that bad. For example, constructing
231 a `vtkTuple<double,4>` in Python looks like this, with the template
232 args in square brackets and the constructor args in parentheses:
234 >>> vtkTuple['float64',4]([1.0, 2.0, 3.0, 4.0])
235 vtkmodules.vtkCommonMath.vtkTuple_IdLi4EE([1.0, 2.0, 3.0, 4.0])
237 The type names are the same as numpy's dtypes: `bool`, `int8`, `uint8`,
238 `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64`, `float32`, and
239 `float64`. Since `int64` is '`long long`', `int` is used for `long`. Also
240 see [Template Keys](#template-keys) in [Advanced Topics](#advanced-topics).
243 # Method Calls {#method-calls}
245 When VTK methods are called from Python, conversion of all parameters from
246 Python to C++ occurs automatically. That is, if the C++ method signature
247 expects an integral type, you can pass a Python `int`, and if C++ expects a
248 floating-point type, you can pass a Python `float` (or any type that allows
249 implicit conversion to `float`).
251 For C++ '`char`' parameters, which are rarely used in VTK, you must pass a
252 string with a length of 1 or 0 bytes. This restricts the value to ASCII,
253 since non-ASCII characters require at least 2 bytes in utf-8. An empty
254 string signifies a null byte, and '\\0' can also be used.
256 A Python `tuple`, `list`, or any other Python sequence can be passed to a VTK
257 method that requires an array or `std::vector` in C++:
260 >>> p = (100.0, 200.0, 100.0)
263 If the method is going to modify the array that you pass as a parameter,
264 then you must pass a Python `list` that has the correct number of slots to
265 accept the returned values. If you try this with a `tuple`, you will get a
266 `TypeError` because `tuple` is immutable.
268 >>> z = [0.0, 0.0, 0.0]
269 >>> vtkMath.Cross((1,0,0),(0,1,0),z)
273 For multi-dimensional array parameters, you can either use a nested list,
274 or you can use numpy array with the correct shape.
276 If the C++ method returns a pointer to an array, then in Python the method
277 will return a tuple if the wrappers know the size of the array. In most
278 cases, the size is hinted in the header file.
281 >>> print(a.GetPosition())
284 Finally, Python `None` is treated the same as C++ `nullptr`, which allows
285 you to pass null objects and null strings:
288 >>> a.SetMapper(None)
289 >>> print(a.GetMapper())
292 ## Wrappable and Unwrappable Methods {#wrappable}
294 A method cannot be used from Python if its C++ parameters or return type
295 cannot be converted to or from Python by the wrappers, or if the method is
296 templated. Common non-convertible types include `std::ostream`, `std::istream`,
297 and all STL container types except for `std::vector` (see below),
298 and any non-trivial pointer type or any pointer to an object whose class is
299 not derived from `vtkObjectBase`.
301 The wrappable parameter types are:
302 * `char`, wrapped as a single ASCII character in a Python `str`
303 * `signed char` and `unsigned char`, wrapped as Python `int`
304 * `short`, `int`, `long` and `long long`, wrapped as Python `int`
305 * `unsigned short` to `unsigned long long`, wrapped as Python `int`
306 * `float` and `double`, wrapped as Python `float`
307 * `size_t` and `ssize_t`, wrapped as Python `int`
308 * `std::string`, wrapped as Python `str` via utf-8 encoding/decoding
309 * typedefs of all the above, for any typedef defined in a VTK header file
310 * `std::vector<T>` where `T` is one of the above, as Python `tuple` or `list`
311 * `const T&` where `T` is any of the above, wrapped as described above
312 * `T[N]` where `T` is a fundamental type, as Python `tuple` or `list`
313 * `T[N][M]` where `T` is a fundamental type, as nested `tuple` or `list`
314 * `T*` where `T` is a fundamental type, as `tuple` or `list`
315 * `vtkObjectBase*` and derived types, as their respective Python type
316 * `vtkSmartPointer<T>` as the Python vtkObjectBase-derived type `T`
317 * `std::vector<vtkSmartPointer<T>>` as a sequence of objects of type `T`
318 * other wrapped classes (like `vtkVariant`), but not pointers to these types
319 * `char*`, as Python `str` via utf-8 encoding/decoding
320 * `void*`, as Python buffer (e.g. `bytes` or `bytearray`)
321 * the parameter list `(void (*f)(void*), void*)` as a Python callable type
323 References like `int&` and `std::string&` are wrapped via a reference proxy
324 type as described in the [Pass by Reference](#pass-by-reference) section
325 below. Non-const references to `std::vector<T>` and other mutable types
326 do not use a proxy, but instead require that a mutable Python object is
327 passed, for example a `list` rather than a `tuple`.
329 A `void*` parameter can accept a pointer in two different ways: either from
330 any Python object that supports the Python buffer protocol (this includes
331 all numpy arrays along with the Python bytes and bytearray types), or from a
332 string that contains a mangled pointer of the form '`_hhhhhhhhhhhh_p_void`'
333 where '`hhhhhhhhhhhh`' is the hexadecimal address. Return-value `void*` will
334 always be a string containing the mangled pointer.
336 Also, a `T*` parameter for fundamental type `T` can accept a buffer object,
337 if and only if it is annotated with the `VTK_ZEROCOPY` hint in the header file.
338 With this hint, a numpy array of `T` can be passed to a `T*` parameter and
339 the VTK method will directly access the memory buffer of the array. Hence the
340 name 'zerocopy', which indicates no copying is done, and that direct memory
343 The `vtkObject::AddObserver()` method has a special wrapping, as discussed
344 in the [Observer Callbacks](#observer-callbacks) section below.
346 ## Conversion Constructors {#conversion-constructors}
348 If a wrapped type has constructor that takes one parameter, and if that
349 constructor is not declared '`explicit`', then the wrappers will automatically
350 use that constructor for type conversion to the parameter type. The
351 wrappers ensure that this conversion occurs in Python in the same manner
352 that it is expected to occur in C++.
354 For example, `vtkVariantArray` has a method `InsertNextItem(v:vtkVariant)`,
355 and `vtkVariant` has a constructor `vtkVariant(x:int)`. So, you can do this:
357 >>> variantArray.InsertNextItem(1)
359 The wrappers will automatically construct a `vtkVariant` from '`1`', and
360 will then pass it as a parameter to `InsertNextItem()`. This is a feature
361 that most C++ programmers will take for granted, but Python users might
364 ## Overloaded Methods {#overloaded-methods}
366 If you call a VTK method that is overloaded, the Python wrappers will choose
367 the overload that best matches the supplied arguments. This matching takes
368 into account all allowed implicit conversions, such as int to float or any
369 conversion constructors that are defined for wrapped objects.
371 Some overloads will be unavailable (not wrapped) either because they are
372 unwrappable as per the criteria described above, or because they are shadowed
373 by another overload that is always perferable. A simple example of this is
374 any methods that is overloaded on C++ `float` and `double`. The Python
375 `float` type is a perfect match C++ `double`, therefore the `float` overload
378 ## Static Methods {#static-methods}
380 A static method can be called without an instance. For example,
382 vtkObject.SetGlobalWarningDisplay(1)
384 Some VTK classes, like vtkMath, consist solely of static methods. For others,
385 like `vtkMatrix4x4`, most of the non-static methods have static overloads.
386 Within Python, the only way to tell if a VTK method is static (other than
387 trying it) is to look at its docstring.
389 ## Unbound Methods {#unbound-methods}
391 When a non-static method is called on the class, rather than on an instance,
392 it is called an unbound method call. An unbound method call must provide
393 'self' as the first argument, where 'self' is an instance of either the class
396 w = vtkRenderWindow()
399 In other words, the wrappers translate Python unbound method calls into
400 C++ unbound method calls. These are useful when deriving a Python class
401 from a wrapped VTK class, since they allow you to call any base class
402 methods that have been overridden in the subclass.
404 ## Operator Methods {#operator-methods}
406 For special classes (the ones not derived from `vtkObjectBase`), some useful
407 C++ operators are wrapped in python. The '`[]`' operator is wrapped for
408 indexing and item assignment, but because it relies on hints to guess which
409 indices are out-of-bounds, it is only wrapped for `vtkVector` and related
412 The comparison operators '`<`' '`<=`' '`==`' '`>=`' '`>`' are wrapped for all
413 classes that have these operators in C++. These operators allow sorting
414 of `vtkVariant` objects with Python.
416 The '`<<`' operator for printing is wrapped and is used by the python
417 `print()` and `str()` commands.
419 ## Strings and Bytes {#strings-and-bytes}
421 VTK uses both `char*` and `std::string` for strings. As far as the wrappers
422 are concerned, these are equivalent except that the former can be `nullptr`
423 (`None` in Python). For both, the expected encoding is ASCII or utf-8.
425 In Python, either `str` or `bytes` can be used to store strings, and both
426 of these can be passed to VTK methods that require `char*` or `std::string`
427 (or the legacy `vtkStdString`). A `str` object is passed to VTK as utf-8,
428 while a `bytes` object is passed as-is.
430 When a VTK method returns a string, it is received in Python as a `str` object
431 if it is valid utf-8, or as a `bytes` object if not. The caller should check
432 the type of the returned object (`str`, `bytes`, or perhaps `None`) if there
433 is any reason to suspect that non-utf-8 text might be present.
435 ## STL Containers {#stl-containers}
437 VTK provides conversion between `std::vector` and Python sequences
438 such as `tuple` and `list`. If the C++ method returns a vector,
439 the Python method will return a tuple:
441 C++: const std::vector<std::string>& GetPaths()
442 C++: std::vector<std::string> GetPaths()
443 Python: GetPaths() -> Tuple[str]
445 If the C++ method accepts a vector, then the Python method can be
446 passed any sequence with compatible values:
448 C++: void SetPaths(const std::vector<std::string>& paths)
449 C++: void SetPaths(std::vector<std::string> paths)
450 Python: SetPaths(paths: Sequence[str]) -> None
452 Furthermore, if the C++ method accepts a non-const vector reference,
453 then the Python method can be passed a mutable sequence (e.g. `list`):
455 C++: void GetPaths(std::vector<std::string>& paths)
456 Python: GetPaths(paths: MutableSequence[str]) -> None
458 The value type of the `std::vector<T>` must be `std::string` or a
459 fundamental numeric type such as `double` or `int` (including
460 `signed char` and `unsigned char` but excluding `char`).
462 ## Smart pointers {#smart-pointers}
464 The wrappers will automatically convert between C++ `vtkSmartPointer<T>`
465 and objects of type `T` (or `None`, if the smart pointer is empty):
467 C++: vtkSmartPointer<vtkObject> TakeObject()
468 Python: TakeObject() -> vtkObject
470 In other words, in Python the smart pointer doesn't look any different
471 from the object it points to. Under the hood, however, the wrappers
472 understand that the smart pointer carries a reference to the object and
473 will take responsibility for deleting that reference.
475 A C++ method can return a vector of smart pointers, which will be seen in
476 Python as a tuple of objects:
478 C++: std::vector<vtkSmartPointer<vtkObject>> GetObjects()
479 Python: GetObject() -> Tuple[vtkObject]
481 If a C++ method expects `std::vector<vtkSmartPointer<T>>` as a parameter,
482 the wrappers will automatically construct the vector from any sequence that
483 is passed from Python. The objects in the sequence must be of type `T` (or
484 a subclass of `T`, or `None`). If not, a `TypeError` will be raised.
486 ## Pass by Reference {#pass-by-reference}
488 Many VTK methods use pass-by-reference to return values back to the caller.
489 Calling these methods from Python requires special consideration, since
490 Python's `str`, `tuple`, `int`, and `float` types are immutable. The wrappers
491 provide a '`reference`' type, which is a simple container that allows
494 For example, consider the following C++ method that uses pass-by-reference:
496 void GetCellAtId(vtkIdType cellId, vtkIdType& cellSize, vtkIdType const*& cellPoints)
498 It requires a reference to `vtkIdType` (a Python `int`), and to
499 `vtkIdType const*` (a tuple of `int`s). So we can call this method as
502 >>> from vtkmodules.vtkCommonCore import reference
503 >>> from vtkmodules.vtkCommonDataModel import vtkCellArray
505 >>> # Build a cell array
506 >>> a = vtkCellArray()
507 >>> a.InsertNextCell(3, (1, 3, 0))
509 >>> # Create the reference objects
511 >>> t = reference((0,))
513 >>> # Call the pass-by-reference method
514 >>> a.GetCellAtId(0, n, t)
521 Some important notes when using pass-by-reference:
522 1. The reference constructor must be given a value of the desired type.
523 The method might use this value or might ignore it.
524 2. Calling the `get()` method of the reference is usually unnecessary,
525 because the reference already supports the interface protocols of the
526 object that it contains.
528 ## Preconditions {#preconditions}
530 One very real concern when using VTK from Python is that the parameters that
531 you pass to a method might cause the program to crash. In particular, it is
532 very easy to pass an index that causes an out-of-bounds memory access, since
533 the C++ methods don't do bounds checking. As a safety precaution, the
534 wrappers perform the bounds check before the C++ method is called:
536 >>> a = vtkFloatArray()
538 Traceback (most recent call last):
539 File "<stdin>", line 1, in <module>
540 ValueError: expects 0 <= id && id < GetNumberOfValues()
542 All precondition checks raise a `ValueError` if they fail, since they are
543 checks on the values of the parameters. The wrappers don't know if C++ is
544 using the parameter as an index, so `IndexError` is not used.
546 Currently the only way to find out if a method has preconditions is to look
547 at the declaration of the method in the C++ header file to see if it has a
550 # Observer Callbacks {#observer-callbacks}
552 Similar to what can be done in C++, a Python function can be called
553 each time a VTK event is invoked on a given object. In general, the
554 callback function should have the signature `func(obj:vtkObject, event:str)`,
555 or `func(self, obj:vtkObject, event:str)` if it is a method of a class.
557 >>> def onObjectModified(object, event):
558 >>> print('object: %s - event: %s' % (object.GetClassName(), event))
561 >>> o.AddObserver(vtkCommand.ModifiedEvent, onObjectModified)
564 object: vtkObject - event: ModifiedEvent
567 ## Call Data {#observer-call-data}
569 In case there is a 'CallData' value associated with an event, in C++, you
570 have to cast it from `void*` to the expected type using `reinterpret_cast`.
571 The equivalent in python is to add a `CallDataType` attribute to the
572 associated python callback method. The supported `CallDataType` values are
573 `VTK_STRING`, `VTK_OBJECT`, `VTK_INT`, `VTK_LONG`, `VTK_DOUBLE`, and
576 The following example uses a function as a callback, but a method or any
577 callable object can be used:
579 >>> from vtkmodules.vtkCommonCore import vtkCommand, VTK_INT
581 >>> def onError(object, event, calldata):
582 >>> print('object: %s - event: %s - msg: %s' % (object.GetClassName(), event, calldata))
584 >>> onError.CallDataType = VTK_INT
586 >>> lt = vtkLookupTable()
587 >>> lt.AddObserver(vtkCommand.ErrorEvent, onError)
589 >>> lt.SetTableRange(2,1)
590 object: vtkLookupTable - event: ErrorEvent - msg: ERROR:
591 In /home/user/VTK/Common/Core/vtkLookupTable.cxx, line 122
592 vtkLookupTable (0x6b40b30): Bad table range: [2, 1]
594 For convenience, the `CallDataType` can also be specified where the function
595 is first declared with the help of the `@calldata_type` decorator:
597 >>> from vtkmodules.util.misc import calldata_type
599 >>> @calldata_type(VTK_INT)
600 >>> def onError(object, event, calldata):
601 >>> print('object: %s - event: %s - msg: %s' % (object.GetClassName(),
604 # Other Wrapped Entities {#other}
606 ## Constants {#constants}
608 Most of the constants defined in the VTK header files are available in Python,
609 and they can be accessed from the module in which they are defined. Many of
610 these are found in the `vtkCommonCore` module, where they were defined as
613 >>> from vtkmodules.vtkCommonCore import VTK_DOUBLE_MAX
615 1.0000000000000001e+299
617 Others are defined as enums, often within a class namespace. If the enum
618 is anonymous, then its values are `int`.
620 >>> vtkCommand.ErrorEvent
623 Constants in the header files are wrapped if they are enums, or if they are
624 const variables of a wrappable scalar type, or if they are preprocessor
625 symbols that evaluate to integer, floating-point, or string literal types.
627 ## Enum Types {#enum-types}
629 Each named enum type is wrapped as a new Python type, and members of the enum
630 are instances of that type. This allows type checking for enum types:
632 >>> from vtkmodules.vtkCommonColor import vtkColorSeries
633 >>> vtkColorSeries.COOL
635 >>> isinstance(vtkColorSeries.ColorSchemes, vtkColorSeries.COOL)
636 >>> cs = vtkColorSeries()
637 >>> cs.SetColorScheme(vtkColorSeries.COOL)
639 Enum classes are wrapped in a manner similar to named enums, except that
640 the enum values are placed within the enum class namespace. For example,
641 `vtkEventDataAction` is an enum class, with '`Press`' as a member:
643 >>> from vtkmodules.vtkCommonCore import vtkEventDataAction
644 >>> vtkEventDataAction.Press
646 >>> isinstance(vtkEventDataAction.Press, vtkEventDataAction)
649 In the first example, the `ColorSchemes` enum type and the `COOL` enum value
650 were both defined in the `vtkColorSeries` namespace. In the second example,
651 the `vtkEventDataAction` enum class was defined in the module namespace,
652 and the `Press` value was defined in the enum class namespace.
654 Note that the VTK enum types behave like C++ enums, and not like the Python
655 enums types provided by the Python '`enum`' module. In particular, all VTK
656 enum values can be used anywhere that an `int` can be used.
658 ## Namespaces {#namespaces}
660 Namespaces are currently wrapped in a very limited manner. The only
661 namespace members that are wrapped are enum constants and enum types.
662 There is no wrapping of namespaced classes or functions, or of nested
663 namespaces. Currently, the wrappers implement namespaces as Python
667 # Docstrings {#docstrings}
669 The wrappers automatically generate docstrings from the doxygen comments in
670 the header files. The Python `help()` command can be used to print the
671 documentation to the screen, or the `__doc__` attributes of the classes
672 and methods can be accessed directly.
674 ## Method Docstrings {#method-docstrings}
676 The method docstrings are formatted with the method signatures first,
677 followed by doxygen comments. The Python method signatures have type
678 annotations, and are followed by the C++ method signatures for
682 InvokeEvent(self, event:int, callData:Any) -> int
683 C++: int InvokeEvent(unsigned long event, void* callData)
684 InvokeEvent(self, event:str, callData:Any) -> int
685 C++: int InvokeEvent(const char* event, void* callData)
686 InvokeEvent(self, event:int) -> int
687 C++: int InvokeEvent(unsigned long event)
688 InvokeEvent(self, event:str) -> int
689 C++: int InvokeEvent(const char* event)
691 This method invokes an event and returns whether the event was
692 aborted or not. If the event was aborted, the return value is 1,
696 Some Python IDEs will automatically show the docstring as soon as you type
697 the name of the method.
699 ## Class Docstrings {#class-docstrings}
701 The class docstrings include a brief description of the class, followed
702 by the name of the superclass, and then the full doxygen documentation,
703 including doxygen markup:
706 vtkMatrix4x4 - represent and manipulate 4x4 transformation matrices
708 Superclass: vtkObject
710 vtkMatrix4x4 is a class to represent and manipulate 4x4 matrices.
711 Specifically, it is designed to work on 4x4 transformation matrices
712 found in 3D rendering using homogeneous coordinates [x y z w]. Many
713 of the methods take an array of 16 doubles in row-major format. Note
714 that OpenGL stores matrices in column-major format, so the matrix
715 contents must be transposed when they are moved between OpenGL and
721 If the class is not derived from `vtkObjectBase`, then it will have one or
722 more public constructors, and these will be included before the comments:
725 vtkSimpleCriticalSection() -> vtkSimpleCriticalSection
726 C++: vtkSimpleCriticalSection()
727 vtkSimpleCriticalSection(isLocked:int) -> vtkSimpleCriticalSection
728 C++: vtkSimpleCriticalSection(int isLocked)
730 vtkSimpleCriticalSection - Critical section locking class
732 vtkCriticalSection allows the locking of variables which are accessed
733 through different threads.
736 ## Template Docstrings {#template-docstrings}
738 Class templates are documented similar to classes, except that they include
739 a 'Provided Types' section that lists the available template instantiations
740 and the C++ template arguments that they correspond to.
743 vtkSOADataArrayTemplate - Struct-Of-Arrays implementation of
746 Superclass: vtkGenericDataArray[vtkSOADataArrayTemplate[ValueTypeT],ValueTypeT]
748 vtkSOADataArrayTemplate is the counterpart of vtkAOSDataArrayTemplate.
749 Each component is stored in a separate array.
752 vtkGenericDataArray vtkAOSDataArrayTemplate
757 vtkSOADataArrayTemplate[char] => vtkSOADataArrayTemplate<char>
758 vtkSOADataArrayTemplate[int8] => vtkSOADataArrayTemplate<signed char>
759 vtkSOADataArrayTemplate[uint8] => vtkSOADataArrayTemplate<unsigned char>
760 vtkSOADataArrayTemplate[int16] => vtkSOADataArrayTemplate<short>
761 vtkSOADataArrayTemplate[uint16] => vtkSOADataArrayTemplate<unsigned short>
762 vtkSOADataArrayTemplate[int32] => vtkSOADataArrayTemplate<int>
763 vtkSOADataArrayTemplate[uint32] => vtkSOADataArrayTemplate<unsigned int>
764 vtkSOADataArrayTemplate[int] => vtkSOADataArrayTemplate<long>
765 vtkSOADataArrayTemplate[uint] => vtkSOADataArrayTemplate<unsigned long>
766 vtkSOADataArrayTemplate[int64] => vtkSOADataArrayTemplate<long long>
767 vtkSOADataArrayTemplate[uint64] => vtkSOADataArrayTemplate<unsigned long long>
768 vtkSOADataArrayTemplate[float32] => vtkSOADataArrayTemplate<float>
769 vtkSOADataArrayTemplate[float64] => vtkSOADataArrayTemplate<double>
772 Unlike classes, the template documentation is formatted similarly regardless
773 of whether the the class template derives from `vtkObjectBase` or not:
776 vtkVector - templated base type for storage of vectors.
778 Superclass: vtkTuple[T,Size]
780 This class is a templated data type for storing and manipulating fixed
781 size vectors, which can be used to represent two and three dimensional
782 points. The memory layout is a contiguous array of the specified type,
783 such that a float[2] can be cast to a vtkVector2f and manipulated. Also
784 a float[6] could be cast and used as a vtkVector2f[3].
789 vtkVector[float64,4] => vtkVector<double, 4>
790 vtkVector[float32,4] => vtkVector<float, 4>
791 vtkVector[int32,4] => vtkVector<int, 4>
792 vtkVector[float64,2] => vtkVector<double, 2>
793 vtkVector[float32,2] => vtkVector<float, 2>
794 vtkVector[int32,2] => vtkVector<int, 2>
795 vtkVector[float64,3] => vtkVector<double, 3>
796 vtkVector[float32,3] => vtkVector<float, 3>
797 vtkVector[int32,3] => vtkVector<int, 3>
801 # Internals and Advanced Topics {#advanced-topics}
803 ## Special Attributes {#special-attributes}
805 Classes and objects derived from `vtkObjectBase` have special attributes, which
806 are only used in very special circumstances.
808 The `__vtkname__` attribute of the class provides the same string that the
809 GetClassName() method returns. With the exception of classes that are
810 template instantiations, it is identical to the `__name__` attribute.
811 For template instantiations, however, `GetClassName()` and `__vtkname__`
812 return the result of calling `typeid(cls).name()` from C++, which provides
813 a platform specific result:
815 >>> vtkSOADataArrayTemplate['float32'].__vtkname__
816 '23vtkSOADataArrayTemplateIfE'
818 This can be used to get the VTK `ClassName` when you don't have an
819 instantiation to call `GetClassName()` on. It is useful for checking the
820 type of a C++ VTK object against a Python VTK class.
822 The `__this__` attribute of the objects is a bit less esoteric, it provides a
823 pointer to the C++ object as a mangled string:
825 >>> a = vtkFloatArray()
827 '_00005653a6a6f700_p_vtkFloatArray'
829 The string provides the hexadecimal address of '`this`', followed by '`p`'
830 (shorthand for *pointer*), and the type of the pointer. You can also
831 contruct a Python object directly from the C++ address, if the address is
832 formatted as described above:
834 >>> a = vtkFloatArray('_00005653a6a6f700_p_vtkFloatArray')
836 <vtkmodules.vtkCommonCore.vtkFloatArray(0x5653a6a6f700) at 0x7f0e7aecf5e0>
838 If you call the constructor on the string provided by `__this__`, you will
839 get exactly the same Python object back again, rather than a new object.
840 But this constructor can be useful if you have some VTK code that has been
841 wrapped with a different wrapper tool, for example with SWIG. If you can
842 get the VTK pointer from SWIG, you can use it to construct Python object
843 that can be used with the native VTK wrappers.
845 ## Wrapper Hints {#wrapper-hints}
847 A wrapper hint is an attribute that can be added to a class, method, or
848 parameter declaration in a C++ header file to give extra information to
849 the wrappers. These hints are defined in the `vtkWrappingHints.h` header
852 The following hints can appear before a method declaration:
853 * `VTK_WRAPEXCLUDE` excludes a method from the wrappers
854 * `VTK_NEWINSTANCE` passes ownership of a method's return value to the caller
856 For convenience, `VTK_WRAPEXCLUDE` can also be used to exclude a whole class.
857 The `VTK_NEWINSTANCE` hint is used when the return value is a `vtkObjectBase*`
858 and the caller must not increment the reference count upon acceptance of the
859 object (but must still decrement the reference count when finished with the
862 The following hints can appear after a method declaration:
863 * `VTK_EXPECTS(cond)` provides preconditions for the method call
864 * `VTK_SIZEHINT(expr)` marks the array size of a return value
865 * `VTK_SIZEHINT(name, expr)` marks the array size of a parameter
867 For `VTK_EXPECTS(cond)`, the precondition must be valid C++ code, and can
868 use any of the parameter names or `this`. Even without `this`, any public
869 names in the class namespace (including method names) will be resolved.
870 See the [Preconditions](#preconditions) section for additional information.
872 For sized array parameters, such as `func(int x[10])`, the wrappers will
873 automatically check the size of the Python sequence that is passed to the
874 method. For bare `T*` pointers (with `T` as a basic integer or float type),
875 The wrappers will only check the size if a `VTK_SIZEHINT` is present.
876 Also, return values of type `T*` will not return a tuple unless there is
877 a size hint for the return value. They will, instead, return a string
878 that provides a mangled pointer of the form '`_hhhhhhhhhhhh_p_void`'
879 where '`hhhhhhhhhhhh`' is the hexadecimal address.
881 The following hints can appear before a parameter declaration:
882 * `VTK_FILEPATH` marks a parameter that accepts a pathlib.Path object
883 * `VTK_ZEROCOPY` marks a parameter that accepts a buffer object
885 More specifically, `VTK_FILEPATH` is used with `char*` and `std::string`
886 parameters to indicate that the method also accepts any object with a
887 `__fspath__()` method that returns a path string. And `VTK_ZEROCOPY` is
888 used with `T*` parameters, for basic integer or float type `T`, to indicate
889 that the Python buffer protocol will be used to access the values, rather
890 than the Python sequence protocol that is used by default.
892 ## Deprecation Warnings {#deprecation-warnings}
894 In addition to the wrapping hints, the Python wrappers are also aware of the
895 deprecation attributes that have been applied to classes and methods. When
896 a deprecated method is called, a `DeprecationWarning` is generated and
897 information about the deprecation is printed, including the VTK version
900 To ignore these warnings, use the following code:
903 warnings.filterwarnings('ignore', category=DeprecationWarning)
905 To see each deprecation warning just once per session,
907 warnings.filterwarnings('once', category=DeprecationWarning)
909 ## Template Keys {#template-keys}
911 The following is a table of common template key names, which are the same as
912 the numpy dtype names. Note that you can actually use numpy dtypes as keys,
913 as well as the native Python types `bool`, `int`, and `float`. There is
914 some danger in using `int`, however, because it maps to C++ `long` which has
915 a platform-dependent size (either 32 bits or 64 bits). Finally, the char
916 codes from the Python `array` module can be used as keys, but they should
917 be avoided since more programmers are familiar with numpy than with the
918 much older `array` module.
920 | C++ Type | Template Key | Type Key | Char Key | IA64 ABI Code |
921 | ------------------ | ------------ | -------- | -------- | ------------- |
922 | bool | 'bool' | bool | '?' | IbE |
923 | char | 'char' | | 'c' | IcE |
924 | signed char | 'int8' | | 'b' | IaE |
925 | unsigned char | 'uint8' | | 'B' | IhE |
926 | short | 'int16' | | 'h' | IsE |
927 | unsigned short | 'uint16' | | 'H' | ItE |
928 | int | 'int32' | | 'i' | IiE |
929 | unsigned int | 'uint32' | | 'I' | IjE |
930 | long | 'int' | int | 'l' | IlE |
931 | unsigned long | 'uint' | | 'L' | ImE |
932 | long long | 'int64' | | 'q' | IxE |
933 | unsigned long long | 'uint64' | | 'Q' | IyE |
934 | float | 'float32' | | 'f' | IfE |
935 | double | 'float64' | float | 'd' | IdE |
937 Since the size of '`long`' and '`unsigned long`' is platform-dependent, these
938 types should generally be avoided.
940 ## Exception Handling {#exception-handling}
942 There are times when an observer might generate a Python exception. Since
943 the observers are called from C++, there is no good way to catch these
944 exceptions from within Python. So, instead, the wrappers simply print a
945 traceback to stderr and then clear the error indicator. The Python program
946 will continue running unless the exception was a `KeyboardInterrupt` (Ctrl-C),
947 in which case the program will exit with an error code of 1.
949 ## Deleting a vtkObject {#deleting-objects}
951 There is no direct equivalent of VTK's `Delete()` method, since Python does
952 garbage collection automatically. The Python object will be deleted
953 when there are no references to it within Python, and the C++ object will
954 be deleted when there are no references to it from within either Python
955 or C++. Note that references can hide in unexpected places, for example if
956 a method of an object is used as an observer callback, the object will not
957 be deleted until the observer is disconnected.
959 The `DeleteEvent` can be used to detect object deletion, but note that the
960 observer will receive a None for the object, since the observer is called
961 after (not before) the deletion occurs:
964 >>> o.AddObserver('DeleteEvent', lambda o,e: print(e, o))
969 If you need to know what object is deleted, the identifying information must
970 be extracted before the deletion occurs:
973 >>> o.AddObserver('DeleteEvent',lambda x,e,r=repr(o): print(e, r))
976 DeleteEvent <vtkmodules.vtkCommonCore.vtkObject(0x55783870f970) at 0x7f1e61678be0>
978 In cases where you need to track down tricky memory issues, you might find
979 it useful to call the `GetReferenceCount()` method of the object directly.
983 A wrapped VTK object (derived from `vtkObjectBase`) is a Python object that
984 holds a pointer to a C++ object (specifically, a `vtkObjectBase*`). The
985 Python object can have attributes that the C++ object knows nothing about.
986 So, what happens to these attributes if the Python object is deleted, but
987 the C++ object lives on? Consider this simple example of storing the C++
988 object in an array and then deleting the Python object:
991 obj.tag = 'FirstObject'
992 va = vtkVariantArray()
993 va.InsertNextValue(obj)
996 When we retrieve the object from the array, we want it to have the '`tag`'
997 attributes that it had we stored it. But you might wonder, aren't all
998 Python-specific attributes deleted along with the Python object? The
999 answer is, no they aren't, they're saved until until the C++ object itself
1002 The wrappers have a special place, which we will call the graveyard, where
1003 'ghosts' of objects are stored when the objects are deleted. The ghost is not
1004 an object, but rather a container for the Python attributes of a deceased
1005 object. If the object ever reappears within Python, usually as a return
1006 value from a C++ method call, then the ghost is resurrected as a new Python
1007 object that has all the attributes of the original Python object.
1009 The graveyard is only used for objects that have unfinished business. If a
1010 Python object has an empty dict and no other special attributes, then it will
1011 not go to the graveyard. Also, if the C++ object is deleted at the same time
1012 as the Python object, then the graveyard will not be used. Each ghost in the
1013 graveyard holds a weak pointer to its C++ object and will vanish when the C++
1014 object is deleted (not immediately, but the next time the graveyard garbage
1017 ## Subclassing a VTK Class {#subclassing}
1019 It is possible to subclass a VTK class from within Python, but this is of
1020 limited use because the C++ virtual methods are not hooked to the Python
1021 methods. In other words, if you make a subclass of `vtkPolyDataAlgorithm`
1022 and override override the `Execute()` method, it will not be automatically
1023 called by the VTK pipeline. Your `Execute()` method will only be called if
1024 the call is made from Python.
1026 The addition of virtual method hooks to the wrappers has been proposed,
1027 but currently the only way for Python methods to be called from C++ code
1028 is via callbacks. The `vtkProgrammableSource` and `vtkProgrammableFilter` are
1029 examples of VTK algorithm classes that use callbacks for execution, while
1030 `vtkInteractionStyleUser` can use observer callbacks for event handling.
1032 ## Wrapping External VTK Modules {#external-wrapping}
1034 If you have your own C++ classes that are based on VTK, and if they are
1035 placed with a VTK module with a vtk.module file, then they can be wrapped
1036 as shown in the [Module Wrapping Example][external-wrapping]. You will
1037 also find the cmake documentation on VTK modules to be useful.
1039 [external-wrapping]: https://gitlab.kitware.com/vtk/vtk/-/blob/release/Examples/Modules/Wrapping
1041 # Experimental Features {#experimental-features}
1043 ## Python Class Overrides {#override}
1045 VTK now supports overriding wrapped classes with Python subclasses. This
1046 enables developers to provide more Python friendly interfaces for certain
1047 classes. Here is a trivial example of an override:
1049 from vtkmodules.vtkCommonCore import vtkPoints
1051 class CustomPoints(vtkPoints):
1054 Once the override is in place, any future `vtkPoints` Python object instances
1055 will be instances of the override class. This behavior is global.
1057 points = vtk.vtkPoints() # returns an instance of CustomPoints
1059 The override can be reversed by setting an override of `None`, but this will
1060 not impact instantions that have already occurred.
1062 vtkPoints.override(None)
1064 If the class has already been overridden in C++ via VTK's object factory
1065 mechanism, then directly applying a Python override to that class will not
1066 work. Instead, the Python override must be applied to the C++ factory
1067 override. For example, on Windows,
1069 @vtkWin32OpenGLRenderWindow.override
1070 class CustomRenderWindow(vtkWin32OpenGLRenderWindow):
1072 window = vtkRenderWindow() # creates a CustomRenderWindow
1074 Please see [Subclassing a VTK Class](#subclassing) for restrictions on
1075 subclassing VTK classes through Python.
1078 ## Stub Files for Type Hinting {#stub-files}
1080 VTK includes a script called [`generate_pyi.py`][generate_pyi] that
1081 will generate pyi stub files for each wrapped VTK module. The purpose of
1082 these files, as explained in [PEP 484][pep_484], is to provide type
1083 information for all constants, classes, and methods in the modules.
1084 Each of these files contain blocks like this:
1087 VTK_DOUBLE_MAX:float
1088 VTK_DOUBLE_MIN:float
1091 class vtkObject(vtkObjectBase):
1092 def AddObserver(self, event:int, command:Callback, priority:float=0.0) -> int: ...
1093 def GetMTime(self) -> int: ...
1095 def GetNumberOfGenerationsFromBaseType(type:str) -> int: ...
1097 def HasObserver(self, event:int, __b:'vtkCommand') -> int: ...
1099 def HasObserver(self, event:str, __b:'vtkCommand') -> int: ...
1101 class vtkAbstractArray(vtkObject):
1102 class DeleteMethod(int): ...
1103 VTK_DATA_ARRAY_ALIGNED_FREE:'DeleteMethod'
1104 VTK_DATA_ARRAY_DELETE:'DeleteMethod'
1105 VTK_DATA_ARRAY_FREE:'DeleteMethod'
1106 VTK_DATA_ARRAY_USER_DEFINED:'DeleteMethod'
1107 def Allocate(self, numValues:int, ext:int=1000) -> int: ...
1109 Python consoles like ipython and IDEs like PyCharm can use the information in
1110 these files to provide hints while you edit the code. These files are
1111 included in the Python packages for VTK, but they can also be built by
1112 executing the `generate_pyi.py` script. To do so, execute the script
1113 with the `vtkpython` executable (or with the regular python executable,
1114 if its paths are set for VTK):
1116 vtkpython -m vtkmodules.generate_pyi
1118 This will place build the pyi files and place them inside the `vtkmodules`
1119 package, where ipython and PyCharm should automatically find them. The
1120 help for this script is as follows:
1122 usage: python generate_pyi.py [-p package] [-o output_dir] [module ...]
1124 -p NAME Package name [vtkmodules by default].
1125 -o OUTPUT Output directory [package directory by default].
1126 -e EXT Output file suffix [.pyi by default].
1127 module Module or modules to process [all by default].
1129 The pyi files are syntactically correct python files, so it is possible to
1130 load them as such in order to test them and inspect them.
1132 [generate_pyi]: https://gitlab.kitware.com/vtk/vtk/-/blob/release/Wrapping/Python/vtkmodules/generate_pyi.py
1133 [pep_484]: https://www.python.org/dev/peps/pep-0484/#stub-files