[vtkusers] patch for turning (almost) all VTK errors into Python exceptions

Sven Prevrhal sven.prevrhal at radiology.ucsf.edu
Fri Aug 4 20:37:32 EDT 2006

I think that's great! I've worked with Python/VTK for a long time now and
that was definitely very annoying.

- Sven

-----Original Message-----
From: Charl P. Botha [mailto:cpbotha at cpbotha.net] 
Sent: Wednesday, August 02, 2006 9:09 AM
To: VTK List; VTK Developers
Subject: [vtkusers] patch for turning (almost) all VTK errors into Python

Hi there (Python)-gang,

I've made a patch for VTK 5.0 which will turn almost all VTK errors
into Python exceptions.  It works around the exception non-safety of
VTK.  Have a look here:


In short, ALL instances of vtkObject descendants are instrumented with
a C++ ErrorEvent handler by the wrapping code in vtkPythonUtil.c.  The
event handler sets up a Python exception by calling PyErr_SetString or
PyErr_None, whichever is relevant.  vtkWrapPython.c generates
wrappings which check PyErr_Occurred() _after_ every VTK method call,
and return NULL if it's true, thus completing the Python exception

For example:

>>> import vtk
>>> a = vtk.vtkXMLImageDataReader()
>>> a.SetFileName('bad filename')
>>> b = vtk.vtkMarchingCubes()
>>> b.SetInput(a.GetOutput())
>>> b.Update()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
RuntimeError: ERROR: In \build\Vtk\Io\vtkXMLReader.cxx, line 173
vtkXMLImageDataReader (013D19C0): Error opening file bad filename

Instead of stdout output or an OutputWindow, we get a neat Python
exception that we can actually do things with.  On Windows, you will
unfortunately see another error message (that of the vtkExecutive) in
an OutputWindow.  This is because the Executive is implicitly created
by pure C++ code.

Fortunately there's a way around this: a vtkOutputWindow child
(globally configured, as is usual) that invokes an ErrorEvent with the
error message instead of outputting anything, thus making use of the
ErrorEvent handler we've added in the wrapping code, and forcing
Executive (and ALL other implicitly created VTK objects) errors to be
transformed into Python exceptions as well.  I have an implementation
of this if anyone is interested.

What do VTK/Python people think?  This definitely fills a niche, and
it could be conditionally included in VTK.  The only drawback is the
extra PyErr_Occurred() call after every VTK method call, and of course
the extra line or two of Python code to set up the new


More information about the vtkusers mailing list