Sunday 29 October 2023

Type hints for matplotlib Axes3D

I have a function that takes a matplotlib 3D axis:

from mpl_toolkits.mplot3d.axes3d import Axes3D


def plot(ax: Axes3D):
    pass

I know how to add a type hint for a 2D axis. Just ax: plt.Axes works perfectly. However, with this mpl_toolkits.mplot3d.axes3d.Axes3D, pylance complains that:

Expected type expression but received (...) -> Unknown Pylance

Sadly, there is no plt.Axes3D equivalent to plt.Axes.

I verified that mpl_toolkits.mplot3d.axes3d.Axes3D works as expected. The following code does not give an error:

fig = plt.figure()
Axes3D(fig)

I went to the definition of Axes3D and found that the problem is the @_docstring.interpd decorator. If I remove it, the pylance warning goes away. The @_api.define_aliases seems to be fine.

I am using python 3.10.12 and matplotlib 3.8.0

Edit: The motivation for the type being Axes3D and not Axes is that otherwise pylance shows a diagnostic that Axes has no method set_zlabel(), etc.



from Type hints for matplotlib Axes3D

No comments:

Post a Comment