lxml-stubs: Type Annotations for lxml
lxml-stubs provides high-quality type annotations (`.pyi` files) for the popular `lxml` library, enabling robust static type checking with tools like MyPy. It is currently at version 0.5.1 and is released irregularly, typically in response to updates in `lxml` or bug fixes in the stubs themselves.
Warnings
- gotcha lxml-stubs provides type information only and does NOT install the lxml library itself. You MUST install both `lxml` and `lxml-stubs` for the type annotations to be useful.
- gotcha lxml-stubs is for static type checking purposes only. It does not alter the runtime behavior or functionality of the lxml library.
- gotcha While efforts are made to keep lxml-stubs in sync with lxml, breaking changes in lxml or new features might not immediately have corresponding type annotations in lxml-stubs, leading to type checker errors or incomplete type coverage.
Install
-
pip install lxml lxml-stubs
Imports
- Element
from lxml import etree; root: etree._Element = etree.fromstring(...)
Quickstart
from lxml import etree
from typing import List
# lxml-stubs provides the type hints for lxml objects
def parse_and_find(xml_string: str, xpath_expr: str) -> List[etree.Element]:
# root will be correctly typed as etree._Element
root: etree._Element = etree.fromstring(xml_string.encode('utf-8'))
# elements will be correctly typed as List[etree.Element]
elements: List[etree.Element] = root.xpath(xpath_expr)
return elements
xml_data = "<root><item id='1'/><item id='2'/></root>"
found_items = parse_and_find(xml_data, "//item")
for item in found_items:
print(f"Found item with ID: {item.get('id')}")
# To verify type checking:
# 1. Save the above code as 'example.py'
# 2. Ensure 'lxml' and 'lxml-stubs' are installed:
# pip install lxml lxml-stubs
# 3. Run a type checker: mypy example.py
# Expected output: Success (no errors)