From e3ce4ee350ee61f9663a518cf5e2896d9e9af1f6 Mon Sep 17 00:00:00 2001 From: santhreal <64453045+santhreal@users.noreply.github.com> Date: Fri, 17 Jul 2026 22:39:42 -0700 Subject: [PATCH] fix: default block width when document has no sections add_table (via _block_width) IndexError'd on sections[-1] when the body has no sectPr. Use the same Letter page/margin defaults already applied when those properties are None. --- src/docx/document.py | 3 +++ tests/test_document.py | 13 ++++++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/docx/document.py b/src/docx/document.py index 73757b46d..777379836 100644 --- a/src/docx/document.py +++ b/src/docx/document.py @@ -232,6 +232,9 @@ def tables(self) -> List[Table]: @property def _block_width(self) -> Length: """A |Length| object specifying the space between margins in last section.""" + # No sectPr (some generators): same Letter defaults as None page/margin values. + if not self.sections: + return Emu(Inches(8.5) - Inches(1) - Inches(1)) section = self.sections[-1] page_width = section.page_width or Inches(8.5) left_margin = section.left_margin or Inches(1) diff --git a/tests/test_document.py b/tests/test_document.py index 53efacf8d..a526a0003 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -19,7 +19,7 @@ from docx.section import Section, Sections from docx.settings import Settings from docx.shape import InlineShape, InlineShapes -from docx.shared import Length +from docx.shared import Inches, Length from docx.styles.styles import Styles from docx.table import Table from docx.text.paragraph import Paragraph @@ -286,6 +286,17 @@ def it_determines_block_width_to_help( assert isinstance(width, Length) assert width == 3500 + def it_uses_default_block_width_when_document_has_no_sections( + self, document: Document, sections_prop_: Mock + ): + # No sectPr: same Letter defaults as None page/margin (avoids sections[-1]). + sections_prop_.return_value = [] + + width = document._block_width + + assert isinstance(width, Length) + assert width == Inches(8.5) - Inches(1) - Inches(1) + # -- fixtures -------------------------------------------------------------------------------- @pytest.fixture