【问题标题】:Pylance in VS Code reports undefined variable with import *VS Code 中的 Pylance 使用 import * 报告未定义的变量
【发布时间】:2021-11-29 05:24:55
【问题描述】:

使用 VSCode v1.61.0 我有一个 python 包,一个名为“tfmodules”的文件夹,里面有一个完整的模块,在 init.py 中我正在这样做:

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')]

在我的代码中我是这样导入的:

from tfmodules import *

然后我用这样的方式调用模块:

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 是包中的一个模块。 代码运行良好,但 Pylance 抛出 36 个 reportUndefinedVariable 实例,每个调用的模块一个。

具体错误(来自模块之一)是:

"fabricbringup" is not defined Pylance(reportUndefinedVariable)

我已经为 vs 代码中的 venv 选择了正确的解释器,并尝试将其添加到 settings.json 文件中:

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

但我仍然从 Pylance 得到错误。我究竟做错了什么?谢谢!

【问题讨论】:

  • 请在您的问题中提供完整的错误信息。

标签: python visual-studio-code pylance


【解决方案1】:

考虑到您不会在运行时添加任何扩展,如何创建一个文件来直接生成对“__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()

结果将如下所示:

#(previous contents of __init__.py)

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

【讨论】:

  • 谢谢。这个周末我花了一点时间来巩固这些模块。添加更多类并保留更少模块在结构上更有意义。因此,手动将模块添加到所有模块相对容易。之后,Pylance 错误消失了。我猜 Pylance 扩展只是不支持动态生成的所有
猜你喜欢
  • 2022-11-01
  • 2020-02-11
  • 2021-08-28
  • 1970-01-01
  • 2023-03-09
  • 2022-08-17
  • 2018-03-21
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多