From 9b80742aed60999a9930e12ed261e24a9bebb4ba Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Wed, 25 Nov 2026 09:42:14 -0800 Subject: [PATCH] Make rendering large templates linear again map_tree() replaced the body element with the rendered tree, and lxml takes quadratic time to move a big subtree between documents. Detaching the old body and attaching a table-heavy new one were both quadratic, so a few thousand variables cost seconds and tens of thousands minutes. Splice the rendered body into the document XML and parse it once, then point the document and its part at the new root. Fixes #74 --- docform/docx/template.py | 16 ++++++++++++++-- tests/unit/test_render.py | 11 +++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/docform/docx/template.py b/docform/docx/template.py index 2111b6a..117ff2d 100644 --- a/docform/docx/template.py +++ b/docform/docx/template.py @@ -724,8 +724,20 @@ def build_xml(self, context, jinja_env=None): def map_tree(self, tree): root = self.docx._element - body = root.body - root.replace(body, tree) + # lxml takes quadratic time to move a large subtree from one document + # to another, so replacing the body element (or moving its children) + # dominated big renders (#74). Splice the rendered body into the + # document's XML and parse it once instead. + xml = etree.tostring(root, encoding="unicode") + start = xml.find("") + if start < 0 or end < 0: + root.replace(root.body, tree) + else: + body_xml = etree.tostring(tree, encoding="unicode") + new_root = docx.oxml.parse_xml(xml[:start] + body_xml + xml[end + len(""):]) + self.docx._element = new_root + self.docx._part._element = new_root # python-docx caches its body wrapper, drop it so reads after # render() see the new body instead of the template one. if hasattr(self.docx, "_Document__body"): diff --git a/tests/unit/test_render.py b/tests/unit/test_render.py index e520bba..b7a9bf0 100644 --- a/tests/unit/test_render.py +++ b/tests/unit/test_render.py @@ -763,3 +763,14 @@ def test_text_box_in_loop_gets_unique_ids(tmp_path): assert len(set(values)) == 3, (path_, values) # the first copy keeps the ids from the template assert etree._Element.xpath(body, "(.//v:shape)[1]/@o:spid", namespaces=ns) == ["_x0000_s1026"] + + +def test_render_swaps_in_one_document_root(make_docx): + tpl = DocxTemplate(make_docx(["{{ a }}", "{{ b }}"], table=[["{{ c }}"]])) + tpl.render({"a": "one", "b": "two", "c": "three"}) + # the document and its part must share the rendered root, or save() + # and python-docx reads would see different trees + assert tpl.docx.element is tpl.docx.part.element + assert [p.text for p in tpl.docx.paragraphs] == ["one", "two"] + assert table_rows(tpl.docx) == [["three"]] + assert body_text(saved(tpl)) == ["one", "two"]