我正在尝试使用 mypy
在一些使用 LXML 的代码中进行类型检查解析 XML 的库。
在我使用 etree.XPath
的每一行中,我都会从 mypy
中得到一个虚假错误。例如,下面的简单脚本
from lxml import etree
NameXPath = etree.XPath("Name/text()")
产生错误
test.py:3: error: "module" has no attribute "XPath"
但脚本运行良好,我的 XPath
在运行时也能正常工作。
我还在导入时尝试了 #type:ignore
,我认为这可能会告诉 mypy
不要对该库进行类型检查,但这并没有抑制错误。
from lxml import etree # type:ignore
NameXPath = etree.XPath("Name/text()")
通过将对 etree.XPath
的调用移动到一个没有任何类型注释的单独函数中,我确实在抑制一些错误方面取得了一些成功,但这似乎是一种 hack 和强制我以笨拙的方式安排我的代码。
我想知道是否有办法完全抑制这些虚假错误,或者可能暗示 etree.XPath
函数确实存在,因为它似乎无法识别自己出来。
明确地说,我实际上并不关心 mypy
是否知道来自 lxml
库的结构的正确类型。我更关心将类型信息放在我自己的类中,我将解析的信息插入其中,所以我想要使用 etree.XPath
进行查询的类型检查函数,找到数据,然后将它们推送到我的脚本中定义的类型注释类中。
mypy
似乎对 etree
中的其他函数没有困难,例如我对 etree.parse
的调用没问题/p>
我目前正在使用 mypy
0.4.4
最佳答案
看起来这是 typeshed 中的错误,社区为 stdlib 和各种第三方库提供的类型注释集合。
特别是,它看起来好像 stubs for lxml完全缺少 XPath 的定义。这可能是一个疏忽——我会尝试在问题跟踪器上提交错误或尝试提交包含修复的拉取请求。
一旦修复此问题,并且 mypy 与最新版本的 typeshed 重新同步,您将需要从 git repo 安装 mypy目前(至少,直到 mypy 0.4.5 在 10 月的某个时候发布)。
同时,您可以通过以下方式解决此问题:
from lxml.etree import XPath # type: ignore
NameXPath = XPath("Name/text()")
# mypy considers NameXPath to have a type of Any
...或者,如果您希望对 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()")
关于python - mypy 虚假错误 : "module" has no attribute "XPath" with etree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39382937/