Type inspection for Python wrappers
The VTK Python wrappers currently provide type information in a manner that is incompatible with other packages and not aligned with any existing standards. The type information is provided in the method docstrings as in the following example, where for each method overload the Python method type is followed by (for informational purposes) the C++ method type:
>>> help(vtk.vtkCellArray.InsertNextCell) Help on method_descriptor: InsertNextCell(...) V.InsertNextCell(vtkCell) -> int C++: vtkIdType InsertNextCell(vtkCell *cell) V.InsertNextCell(int, (int, ...)) -> int C++: vtkIdType InsertNextCell(vtkIdType npts, const vtkIdType pts) V.InsertNextCell(vtkIdList) -> int C++: vtkIdType InsertNextCell(vtkIdList *pts) V.InsertNextCell(int) -> int C++: vtkIdType InsertNextCell(int npts)
The 'V' is a non-standard placeholder for the VTK object, and the method parameters are replaced by types. The C++ method signature is insufficiently informative to justify its presence in the Python docstring.
It would be preferable for the docstrings to format the method type as described in PEP 484. If this was done, then we could write a utility script that could pull the method types out of the docstrings and produce .pyi files that could be used by type checkers. The resulting docstrings would start like this:
InsertNextCell(cell:vtkCell) -> int InsertNextCell(npts:int, pts:Sequence[int]) -> int InsertNextCell(pts:vtkIdList) -> int InsertNextCell(npts:int) -> int
A script could use the docstrings to generate the following code for a .pyi file:
import typing import vtkCommonCorePython import vtkCommonDataModelPython class vtkCellArray(vtkCommonCore.vtkObject): @overload def InsertNextCell(cell:vtkCommonDataModelPython.vtkCell) -> int: ... @overload def InsertNextCell(npts:int, typing.Sequence[int]) -> int: ... @overload def InsertNextCell(pts:vtkCommonCorePython.vtkIdList) -> int: ... @overload def InsertNextCell(npts:int) -> int: ...
The as-yet-unwritten script would generate the .pyi file by iterating over the docstrings of all of the methods in the class. The script would have to have knowledge of the 'typing' module and of the VTK package structure. Also, we would have to provide a docstring for the
__init__ slot, which is currently not done by the VTK wrappers.
Note that type information can also be stored in the
__annotations__ attribute of the method (or method descriptor) as described in PEP 3107. However, it is unclear how this could be done for overloaded methods, so it is unlikely that
__annotations__ will be used with VTK.
For a description of how .pyi files might be included with VTK package distributions, see PEP 561.