1

When looking at the documentation of the pandas method .hist(), it is written that it returns a matplotlib.AxesSubplot or numpy.ndarray. However when trying to type hint with hist: matplotlib.AxesSubplot = df.hist() it doesn't work (cf. error message in the title of the post).

When printing type() Python returns: Out[1]: matplotlib.axes._subplots.AxesSubplot. Should I type hint my variable hist with this (matplotlib.axes._subplots.AxesSubplot)?

1 Answer 1

1

Lovely question, made me dive into some new stuff I did not know. Here is my understanding of it:

It is not actually a class but a dynamic class created by a class factory, checking the mro (like type(df.hist()).mro()) of it you can see the whole inheritance.

enter image description here

Looking at the inheritance of AxesSubplot we see SubplotBase and Axes, so it inherits from both of these but essentially it is an Axes in a Subplot. Based on this I would have gone for matplotlib.axes._axes.Axes for type hinting.

Here is a good discussing that I derived these results from: https://github.com/matplotlib/matplotlib/issues/18222

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. Though, not sure I follow everything, if it is an Axes in a Subplot, why not simply use matplotlib.axes._subplots.AxesSubplot. I didn't want to use it because of the underscore meaning it's a private class (I might be wrong?), but your suggestion matplotlib.axes._axes.Axes does call a private class as well?
I thought the reason you didn't use it is because when you type hint matplotlib.axes._subplots.AxesSubplot or try to import from matplotlib.axes._subplots import AxesSubplot you can't because it is a dynamically generated class and there is no exact reference to that hence your AttributeError that is why I would have used a class it inherits from and carries its properties for type hinting. I understand the hesitation about it being a private class and I think for type hinting it should not be a problem, you are not using that class just pointing to that for more information in your code.
"Based on this I would have gone for matplotlib.axes._axes.Axes for type hinting." Actually matplotlib.Axes works and is recognised (does point to matplotlib.axes._axes.Axes). So I went for that instead of matplotlib.axes._axes.Axes which included the "private path".
I see, glad you found a solution that you are comfortable with!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.