types-lxml

2026.2.16 · active · verified Fri Apr 10

types-lxml, version 2026.2.16, provides comprehensive external type annotations (stubs) for the `lxml` library, enabling static type checking with tools like MyPy and Pyright, and improving IDE support. It is actively maintained with frequent updates, often releasing multiple versions per month, and is a more complete fork of the original `lxml-stubs` project. It aims to cover major lxml submodules like `lxml.etree`, `lxml.html`, and `lxml.objectify` for Python 3.9 and newer.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic XML parsing, element finding, and modification using `lxml.etree`. `types-lxml` enhances this experience by providing accurate type hints for `lxml` objects like `_Element` and `_ElementTree`, which are consumed by static type checkers and IDEs.

from lxml import etree

# Example XML string
xml_string: str = '<root><item id="1">Apple</item><item id="2">Banana</item></root>'

# Parse the XML string
root: etree._Element = etree.fromstring(xml_string)

# Find an element by tag name
item: etree._Element | None = root.find('item')
if item is not None:
    print(f"First item: {item.text}")

# Find all elements with a specific tag
all_items: list[etree._Element] = root.findall('item')
for i, element in enumerate(all_items):
    item_id: str | None = element.get('id')
    print(f"Item {i+1} (ID: {item_id}): {element.text}")

# Create a new element and append it
new_element: etree._Element = etree.SubElement(root, 'item', id='3')
new_element.text = 'Cherry'

# Print the modified XML
print("\nModified XML:")
print(etree.tostring(root, pretty_print=True).decode())

view raw JSON →