What is the best way to use Python VTK?

If ask gpt, it tells me to import vtk like

import vtk
cube = vtk.vtkCubeSource()

but on vtk example, most cases use vtkmodule like

import vtkmodules.vtkInteractionStyle
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints

I’m a python vtk beginner and I prefer the first method, so I wonder what is the difference between these two kinds of usage and maybe they are suitable for different scenarios?

VTK consists of around 120 different modules. When you “import vtk”, it imports all of them and puts their contents into the vtk module for convenience. However, with “from vtkmodules.vtkSomething import something”, you import only the modules that your program needs. This allows your program to start up faster, since fewer modules are loaded.

For most uses of VTK, the difference in start-up speed is not important, so you should use whichever method you prefer. For example, if write a GUI application, then an extra second or two of startup time doesn’t matter. But if you write a utility program that just does some VTK processing and then saves the result, and if the processing itself only takes a fraction of a second, then a startup time of one or two seconds is a performance killer.

3 Likes

Also, if you like to convert import vtk to the faster and more verbose imports, you can find a script in the VTK source distribution for doing that. It is located in Utilities/Maintenance/ModernizePythonImports.py

3 Likes

Thank you, this python script is amazing~
I pip installed python vtk and I can’t find it in python site-package, but I do find it in source distribution.
I once thought source distribution is c++ version vtk, why this fantastic python script is not in pip version?
Thank you again for your suggestion.

Also if you are trying to figure out quickly what vtkmodules subpackage that a class is in, if you import vtk and then search for the help on the class - it tells you the vtkmodules subpackage in the top line: help(vtk.vtkPolyData) … although Jens’ answer is pretty awesome.

1 Like

Other easy ways to find the module for a class:

>>> import vtk
>>> vtk.vtkPolyData.__module__
'vtkmodules.vtkCommonDataModel'
>>> vtk.vtkPolyData
<class 'vtkmodules.vtkCommonDataModel.vtkPolyData'>
3 Likes