声明可选依赖性的类型注释
可以说,我想声明来自库的可选依赖性的输入类型。我可以选择将其设置为字符串,至少使Python感到高兴(例如,不抱怨丢失的名称)。但是,Mypy当然不知道该如何处理这种缺失类型。是否有任何解决方案, 必须安装可选依赖性?
例如,我的库选择取决于matplotlib。某些功能将轴对象作为输入。
def some_plotting_func(data, ax: "matplotlib.axes.Axes" = None):
if ax is None:
from matplotlib.pylab import subplots
_, ax = subplots(1, 1)
抱怨,因为Matplotlib没有被导入(我不想将其加载到模块顶部,但只有在some_plotting_func
的功能主体中需要时,只有在要求上加载它。
然后Mypy 错误:名称“ matplotlib”未定义[名称定义]
Lets say I want to declare an input type originating from an optional dependency of my library. I have the option to set it as a string, at least to make Python happy (e.g. not complain about the missing name). But then Mypy will of course not know what to do about this missing type. Is there any solution, without having to install the optional dependency?
For example, my library depends optionally on Matplotlib. And some function takes an Axes object as input.
def some_plotting_func(data, ax: "matplotlib.axes.Axes" = None):
if ax is None:
from matplotlib.pylab import subplots
_, ax = subplots(1, 1)
Then MyPy complains, as matplotlib is not being imported (and I do not want to load it on module top, but only if demanded inside the function body of some_plotting_func
.
MyPy output:error: Name "matplotlib" is not defined [name-defined]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能必须在CMD中安装matplotlib。
Probably you have to install matplotlib in cmd.