On this page
pyexpat
Prev: pydoc_data | Up: stdlib_module | Next: queue
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — pyexpat
Tags: #public #python3 #stdlib
Import
import pyexpat
Overview
Low-level C-extension wrapper around the Expat streaming, non-validating XML parser (also accessible as xml.parsers.expat). Reach for pyexpat when you need maximum throughput and minimal memory footprint on huge XML streams via event callbacks (StartElementHandler, EndElementHandler, CharacterDataHandler); for most tasks, xml.etree.ElementTree in xml is simpler.
Quick Start
import pyexpat
events: list[tuple[str, str]] = []
parser = pyexpat.ParserCreate()
parser.StartElementHandler = lambda name, attrs: events.append(("start", name))
parser.CharacterDataHandler = lambda data: events.append(("text", data)) if data.strip() else None
parser.EndElementHandler = lambda name: events.append(("end", name))
parser.Parse(b"<note><msg>hi</msg></note>", True)
assert events == [("start", "note"), ("start", "msg"), ("text", "hi"), ("end", "msg"), ("end", "note")]
Implementation Walkthrough
1. Streaming Large Files in Chunks
Feed bytes incrementally with Parse(chunk, isfinal=False) and finish with Parse(b"", True) so multi-gigabyte XML files use constant memory:
import pyexpat
def count_elements(chunks: list[bytes], target_tag: str) -> int:
count = 0
parser = pyexpat.ParserCreate()
def on_start(name: str, attrs: dict[str, str]) -> None:
nonlocal count
if name == target_tag:
count += 1
parser.StartElementHandler = on_start
for chunk in chunks:
parser.Parse(chunk, False)
parser.Parse(b"", True)
return count
assert count_elements([b"<items><item/>", b"<item/></items>"], "item") == 2
Gotchas & Boundaries
CharacterDataHandlermay fire multiple times for one text node: Expat can split character data across buffer boundaries or entity boundaries. Always accumulate chunks in a list and join them onEndElementHandler.- Disable DTDs / entity expansion on untrusted XML: Expat protects against billion-laughs via amplification limits in modern Python, and you can also reject
<!DOCTYPEor external entities by settingStartDoctypeDeclHandlerto raise an error (or usedefusedxml). - One-shot parser instances: A
pyexpatparser cannot be reused afterParse(..., True); create a fresh parser withParserCreate()for each document.
Common Functions
- pyexpat.ErrorString() —
ErrorString(code, /)— Returns string error for given number. - pyexpat.ParserCreate() —
ParserCreate(...)— Return a new XML parser object.
Classes & Objects
- pyexpat.error —
pyexpat.errorclass. (Methods:.add_note(),.with_traceback()) - pyexpat.ExpatError —
pyexpat.ExpatErrorclass. (Methods:.add_note(),.with_traceback()) - pyexpat.XMLParserType — XML parser (Methods:
.ExternalEntityParserCreate(),.GetBase(),.GetInputContext(),.GetReparseDeferralEnabled(),.Parse(),.ParseFile())
Constants & Attributes
pyexpat.EXPAT_VERSION(str) ='expat_2.7.4'pyexpat.XML_PARAM_ENTITY_PARSING_ALWAYS(int) =2pyexpat.XML_PARAM_ENTITY_PARSING_NEVER(int) =0pyexpat.XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE(int) =1pyexpat.expat_CAPI(PyCapsule) =<capsule object "pyexpat.expat_CAPI" at 0x10a6fc950>pyexpat.features(list) =[('sizeof(XML_Char)', 1), ('sizeof(XML_LChar)', 1), ('XML...pyexpat.native_encoding(str) ='UTF-8'pyexpat.version_info(tuple) =(2, 7, 4)
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/pydoc_data
- tuts/python3/stdlib_module/pyexpat/error
- tuts/python3/stdlib_module/pyexpat/ErrorString
- tuts/python3/stdlib_module/pyexpat/ExpatError
- tuts/python3/stdlib_module/pyexpat/ParserCreate
- tuts/python3/stdlib_module/pyexpat/XMLParserType
- tuts/python3/stdlib_module/queue
- tuts/python3/stdlib_module/stdlib_module
Related notes
- tuts/python3/stdlib_module/pydoc_data Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pyexpat/error Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pyexpat/ErrorString Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pyexpat/ExpatError Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pyexpat/ParserCreate Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pyexpat/XMLParserType Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/queue Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib