昨天我从
3.11
升级到了python3.12
。
我使用的编辑器是VScode
。
当我将标准模式与 matplotlib (来自官方文档)一起使用时,智能感知无法识别类型,因此按点无法公开方法和属性。
这是可重现的代码:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
colours = ['red', 'blue', 'red', 'orange']
ax.bar(fruits, counts, label=colours, color=colours)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()
如果我明确输入提示,那么它就有效。但这非常笨重并且看起来很糟糕。
我现在必须这样做:
import matplotlib.pyplot as plt
from matplotlib.figure import Figure # added this
from matplotlib.axes import Axes # added this
fig, ax = plt.subplots()
fig: Figure # added this
ax: Axes # added this
fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
colours = ['red', 'blue', 'red', 'orange']
ax.bar(fruits, counts, label=colours, color=colours)
ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')
plt.show()
据我所知,早期版本的 python 从未遇到过这个问题。
如何解决此问题,以便我不必显式键入提示
fig
和 ax
?
在这两个版本的 Python 中,我都没有在
ax.
之后看到 Intellisense。原因是 matplotlib 3.8.0 中的 plt.subplots
返回 tuple[Figure, Any]
,因此 Pylance 不知道 ax
的类型。 Matplotlib 3.8.0 添加了 Pylance 信任的内联类型,因为该库是 py.typed
。
也许除了不同的 Python 版本之外,您还使用不同的 matplotlib 版本?如果我安装 matplotlib 3.7.3 而不是 3.8.0,则 Pylance 使用其捆绑的 matplotlib 存根并将
ax
视为 Axes
对象。