Skip to content
Advertisement

Declare type annotation for optional dependency

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]

Advertisement

Answer

Probably you have to install matplotlib in cmd.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement