lxml / lxml-stubs

Type stubs for the lxml package
Other
43 stars 28 forks source link

[mypy] Argument "namespaces" to "xpath" has incompatible type "Dict[Optional[str], str]"; expected "Optional[Mapping[str, Union[str, bytes]]]" #82

Closed cmason3 closed 10 months ago

cmason3 commented 1 year ago

I am trying to use mypy to check my codebase and I can't fix the following error. It seems to be an issue with lxml and namespaces - the below XML makes use of the junos namespace for the junos:changed attribute:

<interfaces xmlns:junos="http://xml.juniper.net/junos/*/junos">
    <interface>
        <name>et-0/1/0</name>
        <description junos:changed='changed'>## [DCI] 100GE Circuit to ROUTER-01 (et-0/1/0) ##</description>
    </interface>
    <interface>
        <name>et-0/1/1</name>
        <description>## 100GE Link to SPINE-01 (et-0/0/0) ##</description>
    </interface>
    <interface>
        <name>et-0/1/2</name>
        <description>## 100GE Link to SPINE-02 (et-0/0/0) ##</description>
    </interface>
</interfaces>

I am then using the following Python code to perform an xpath query:

s_xml = "<AS ABOVE>"
s_path = "//interfaces/interface[starts-with(name, 'et')]/description[@junos:changed]/text()"
p_xml = etree.fromstring(s_xml, parser=etree.XMLParser(remove_comments=True, remove_pis=True))
xml = p_xml.xpath(s_path, namespaces=p_xml.nsmap)

I am extracting the namespace from the XML and then passing it to the xpath query, but mypy complains about the following:

program.py:66: error: Argument "namespaces" to "xpath" of "_Element" has incompatible type "Dict[Optional[str], str]"; expected "Optional[Mapping[str, Union[str, bytes]]]"  [arg-type]

Surely the output from one lxml function should be the required type to be used as input for another?

Python 3.9 with the following:

mypy==1.0.0 lxml==4.9.2 types-lxml==2022.11.8