Fast Python3 VTK import

EDIT: This is post is deprecated by VTK 8 which allow to import modules one by one.

This is an update of this post for Python3.

The Python VTK module is long to import because it load all the native VTK libraries which most of the time you won’t need. With VTK already in memory (disk cache):

time python3 -c "import vtk"

real 0m0.623s
user 0m0.554s
sys 0m0.069s

Here is a way to make it fast:

class _NopLoader(importlib.abc.Loader):
    """ A loader which does not load """
    def exec_module(self, module):
        pass

class _FastVTKLoader(object):
    def __init__(self, modules):
        self.modules = modules

    def imp(self):
        if not sys.meta_path:
            sys.meta_path.append(self)
        else:
            sys.meta_path[0] = self
        import vtk
        sys.meta_path.remove(self)
        return vtk

def find_spec(self, name, path, target=None):
    if name.startswith("vtk.vtk") and not name.endswith("Python"):
        vm = name[7:]
        if vm not in self.modules:
            return importlib.machinery.ModuleSpec(name, _NopLoader())

vtk = _FastVTKLoader(["CommonCore", "CommonDataModel", "IOXML",
    "FiltersCore", "FiltersPoints"]).imp()
import vtk.util.numpy_support
$ time python3 myvtkloader.py

real 0m0.096s
user 0m0.076s
sys 0m0.020s

#python, #vtk