Search code examples
pythonvisual-studio-codepylint

Why do I get 2 error messages when writing Python code using Visual Studio Code?


I have a lot of datamodels in a datamodel/ directory and I don't want to import them one by one so I did:

from datamodel import *  # pylint:disable=unused-wildcard-import

and then further on I did:

datamodel_file.DataModelClass(db_server)

I get the following errors in VS Code:

Undefined variable 'datamodel_file' (pylint(undefined-variable)[22,27]
Undefined variable: 'datamodel_file' (Python(undefined-variable)[22,27]

A few problems with this:

  1. I don't understand why VS Code/PyLint thinks that this variable is undefined as the code runs fine when I debug it
  2. Why are there 2 error messages?
  3. I tried to disable the pylint message as a quick try-and-see-what-happens by doing: datamodel_file.DataModelClass(db_server) # pylint:disable=undefined-variable This has the effect of disabling the error from pylint but that other error from Python still remains.

How should I fix this error?


Solution

  • Using import * is discouraged outside of the REPL because of situations like this where you can't tell from introspecting the code where the name is supposed to come from. Chances are datamodel specifies datamodel_file in some funky way that Pylint or the language server can't figure out.

    As for the two linter warnings, that's because you're running two tools at once: Pylint and the Python language server which provides basic linting. If you want to disable the Python language server one please see the docs on its settings.

    But the best way to solve this is simply to not use import *. Either do import datamodel and then use datamodel.datamodel_file (or do something like import datamodel as dm; dm.datamodel_file). Or you can use from datamodel import datamodel_file.