lxml-stubs: Type Annotations for lxml

0.5.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `lxml` with type annotations. By installing `lxml-stubs` alongside `lxml`, type checkers like MyPy can correctly infer and validate the types of `lxml` objects and methods.

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)

view raw JSON →