mypy spurious错误:"module"没有带etree的属性"XPath"

ugl*_*ote 6 python lxml mypy

我试图mypy在一些使用LXML库解析XML的代码中进行类型检查.

在我使用的每一行上etree.XPath,我都会收到虚假错误mypy.例如,以下琐碎的脚本

from lxml import etree    
NameXPath = etree.XPath("Name/text()")
Run Code Online (Sandbox Code Playgroud)

生成错误

test.py:3: error: "module" has no attribute "XPath"
Run Code Online (Sandbox Code Playgroud)

但脚本运行正常,我XPath的运行正常.

我也尝试#type:ignore过导入,我认为可能会告诉我mypy不要对该库进行类型检查,但这并没有抑制错误.

from lxml import etree # type:ignore    
NameXPath = etree.XPath("Name/text()")
Run Code Online (Sandbox Code Playgroud)

通过将调用移动etree.XPath到一个没有任何类型注释的单独函数,我确实取得了一些成功,但这看起来像是一个黑客,并迫使我以尴尬的方式安排我的代码.

我想知道是否有办法完全抑制这些虚假错误,或者可能暗示etree.XPath函数确实存在,因为它似乎无法自己解决这个问题.

要清楚,我实际上并不关心mypy知道从lxml库中出来的结构的正确类型.我更关心将类型信息放在我自己的类上,我将解析后的信息推入,所以我想要使用类型检查函数etree.XPath来进行查询,查找数据,然后将它们推入类型 -在我的脚本中定义的带注释的类.

mypy似乎没有其他功能的困难etree,例如它对我的电话很好etree.parse

我目前正在使用mypy0.4.4

Mic*_*x2a 5

看来这是typeshed中的一个错误,这是stdlib和各种第三方库的社区贡献的类型注释集合。

特别是,看起来lxml存根似乎完全缺少XPath的定义。这可能是疏忽大意-我将尝试在问题跟踪器上提交错误,或尝试提交包含修复程序的请求请求。

一旦解决此问题,并且mypy用最新版本的shedshed重新同步,您将需要暂时从git repo安装mypy (至少,直到mypy 0.4.5在十月的某个时候出来)。

同时,您可以通过以下方法解决此问题:

from lxml.etree import XPath  # type: ignore
NameXPath = XPath("Name/text()")
# mypy considers NameXPath to have a type of Any
Run Code Online (Sandbox Code Playgroud)

...或者,如果您希望对XPath进行更具体的定义,请执行以下操作:

import typing

if typing.TYPE_CHECKING:
    # typing.TYPE_CHECKING is always False at runtime, so this
    # branch is parsed by typecheckers only
    class XPath:
        # Provide a method header stubs with signatures to fool
        # mypy into understanding what the interface for XPath is
else:
    # Actually executed at runtime
    from lxml.etree import XPath  # type: ignore

NameXPath = XPath("Name/text()")
Run Code Online (Sandbox Code Playgroud)