Why does VSCode show 'problems' which do not exist?

Viewed 203

I'm using VSCode with the python extension. The 'problems' tab as well as the indicators on the 'explorer' tab and the red underline in the code view itself all show there to be an error, even though the error isn't real.

After importing matplotlib.pyplot as plt, the code uses plt.cm.RdBu. VSCode is presenting the error that matplotlib.cm has no member RdBu.

There are two issues here:

  • Unless I'm just mistaken, plt.cm.RdBu ought to be equivalent to matplotlib.pyplot.cm.RdBu, not matplotlib.cm.RdBu. It seems to be interpreting that incorrectly.
  • But regardless of that, both cm and pyplot.cm actually do have an attribute called RdBu, both of which I was able to pull up information for using help(). The code runs perfectly and python throws no errors.

Why is VSCode telling me this is an error when it isn't? Is this just a bug or could it be a misconfiguration?

1 Answers

Unfortunately, there doesn't seem to be a way to fix this issue. The reason that VS Code, or more specifically, the linter used by the Python extension isn't picking up matplotlib.pyplot.cm.RdBu, or any other colormaps defined in cm is because they're defined dynamically. If you try looking inside cm.py, you'll only find this:

cmap_d = _gen_cmap_d()
locals().update(cmap_d)

Essentially, instead of being statically defined like RdBu = ..., these colormaps are defined dynamically by being injected into the module's global namespace at runtime. Even though this works fine when you run it, unfortunately it means that there's no way for the linter to know that names such as RdBu exist in the namespace until runtime. And as most linters such as pylint and flake8 are static code analysis tools that never actually execute the code, it's impossible for them to detect the existence of these colormaps.

Related