2

I am trying to add type hints for data returned by plt.subplots. That works fine for plt.Axes, but I can't seem to find a solution for Figure.

Any ideas what I could do?

An abbreviated version of my code is:

def draw_graph() -> Tuple[plt.Figure, plt.Axes]: 

    fig, ax = plt.subplots(figsize=(14,10))
    return (fig, ax)

I get the message: "Figure" is not a known member of module Pylance

spst
  • 50
  • 5
  • 1
    Does this answer your question? [How can I get stub files for \`matplotlib\`, \`numpy\`, \`scipy\`, \`pandas\`, etc.?](https://stackoverflow.com/questions/60247157/how-can-i-get-stub-files-for-matplotlib-numpy-scipy-pandas-etc) – Daniil Fajnberg Dec 16 '22 at 15:58
  • unfortunately, that did not get me very far. data-science-types has been archived and does not contain Figure anyway. – spst Dec 19 '22 at 07:13
  • The main point was this: _"There is no official support for these libraries stubs"_. Unfortunately, you'll have to try and find third-party stubs, write your own stubs (as you need them), or make exceptions in your annotations (e.g. via `type: ignore`) in places that rely on matplotlib types. That library seems to come from a time, when annotating Python modules was uncommon (or maybe even impossible) and by now it is so extremely bloated that adding correct type annotations throughout it would be a giant project in itself. https://github.com/matplotlib/matplotlib/issues/20504 – Daniil Fajnberg Dec 19 '22 at 09:39
  • That was more or less my conclusion as well. So what I did was to add `# type ignore` comments to the offending lines. Not really satisfying, but it seems the best I can do... – spst Dec 21 '22 at 06:43

1 Answers1

2

With the latest Matplotlib (v3.7.1) I was able to do the following:

import matplotlib.pyplot as plt
import matplotlib.figure

def draw_graph() -> Tuple[matplotlib.figure.Figure, plt.Axes]: 

    fig, ax = plt.subplots(figsize=(14,10))
    return (fig, ax)

I haven't tested using plt.Figure, but my IDE (i.e., VS Code) was not giving me any errors with plt.Figure.

qwerty
  • 101
  • 1
  • 9
  • 1
    I had to change the second line to `import matplotlib.figure`. Then it seems to work for me. – spst Apr 12 '23 at 10:23
  • You're right, I had to use import `matplotlib.figure` as well for another environment I was using. Thanks for the recommendation, I've updated the answer response to reflect the better solution. – qwerty Apr 13 '23 at 16:20