Home > Enterprise >  Pylance in VS Code reports undefined variable with import *
Pylance in VS Code reports undefined variable with import *

Time:10-11

Using VSCode v1.61.0 I have a python package, a single folder named "tfmodules" with a whole lotta modules, and in the init.py I'm doing this:

from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

In my code I import it like so:

from tfmodules import *

Then I call the modules with something like this:

def write(aci_topology_model, provider_source, provider_version):
    with open('fabric-bringup.tf', 'w') as f:
        x = fabricbringup.tf_write_fabric_bringup(aci_topology_model, provider_source, provider_version)
        f.write(x)

fabricbringup is a module in the package. The code works just fine, but Pylance is throwing 36 reportUndefinedVariable instances, one for each module called.

The specific error (from one of the modules) is:

"fabricbringup" is not defined Pylance(reportUndefinedVariable)

I have selected the proper interpreter for the venv in vs code, and I tried adding this to the settings.json file:

"python.analysis.extraPaths": ["tfmodules", "/home/aj/projects/python/dcnet-aci-lld-convert/tfmodules"]

But I still get the errors from Pylance. What am I doing wrong? Thanks!

CodePudding user response:

Considering you will not be adding any extensions at runtime how about creating a file that will generate all references directly to "__init__.py"?

if __name__ == "__main__":
    from os.path import dirname, basename, isfile, join
    import glob
    modules = glob.glob(join(dirname(__file__), "*.py"))
    print(join(dirname(__file__), "*.py"))
    __all__ = ["\t\""  basename(f)[:-3] "\",\n" for f in modules if isfile(f) and not f.endswith('__init__.py') and not f.endswith('__add__manager.py')]

    f = open(join(dirname(__file__), "__init__.py"), "a")
    f.write("__all__ = [\n")
    f.writelines(__all__)
    f.write("]\n")
    f.close()

Result will look something like this:

#(previous contents of __init__.py)

__all__ = [
    "file1",
    "file2",
]
  • Related