__getitem__ method not defined on Axes

Attempting to access Axes items produces Pylance error complaining about getitem method not defined, but the code seems to work correctly. Here’s a snippet:

import matplotlib.pyplot as plt
fig, axs = plt.subplots(4, 1, sharex="all")
axs[2].set_ylabel("Temperature", color="tab:red")

"__getitem__" method not defined on type "Axes"

Apologies if I’m missing something stupid here but I’m a relative newcomer to pyplot/matplotlib

The result of plt.subplots is either an Axes or a NumPy array of Axes. The type definitions are incorrectly stating it is just Axes.

We do not maintain the type definitions though, so you will have to report that to Pylance (or maybe Pyright; I’m not sure where the type definitions come from).

Thanks for the explanation. At runtime axs is an array which is why my code works ok. So nothing to worry about, just annoying.

If you always want a numpy array back you can do

In [19]: fig, ax = plt.subplots(squeeze=False)

In [20]: ax
Out[20]: array([[<AxesSubplot:>]], dtype=object)

In [21]: type(ax)
Out[21]: numpy.ndarray

In [22]: ax.shape
Out[22]: (1, 1)

which will ensure you are always returned a 2D numpy array of Axes objects. The default is to “do what I mean” and squeeze out any singleton dimensions.