Skip to content

fix: do not leave an unreturned table behind when the style is undefined (#1631) - #1637

Open
Uneadlight wants to merge 1 commit into
python-openxml:masterfrom
Uneadlight:fix/1631-add-table-style-rollback
Open

Uneadlight wants to merge 1 commit into
python-openxml:masterfrom
Uneadlight:fix/1631-add-table-style-rollback

Conversation

@Uneadlight

Copy link
Copy Markdown

Document.add_table() assigns table.style = style after _Body.add_table() has already appended the w:tbl element to the body. When the style name is not defined in the document, Table.style raises KeyError — and the half-built table stays in the body. The caller gets an exception and no table object, so it cannot remove the stray table either.

This rolls the table back before re-raising, so a failed call leaves the document exactly as it was:

table = self._body.add_table(rows, cols, self._block_width)
try:
    table.style = style
except KeyError:
    table._tbl.getparent().remove(table._tbl)
    raise
return table

The KeyError still propagates (the caller should still learn the style name was wrong) — only the side effect is undone. This also matches what save()-then-reopen showed before the fix: the stray table was really written to the file, not just kept in memory.

The regression test builds a real document (no mocks), calls add_table() with an undefined style and asserts document.tables stays empty. It is a module-level it_... function because python_functions in pyproject.toml only collects that prefix.

Test results locally (Windows, Python 3.12, pyparsing==3.1.1 — 3.3.3 trips filterwarnings = ["error"]):

  • before: 53 failed, 1547 passed, 9 errors
  • after: 53 failed, 1548 passed, 9 errors

Same failure set (all pre-existing Windows temp-file/path issues), +1 new passing test. ruff check and ruff format --check are clean.

Fixes #1631.

`Document.add_table()` set `table.style` after the table had already been
appended to the body. When the style name was not defined in the document the
`KeyError` propagated, but the half-built table stayed behind and the caller
had no handle to remove it (issue python-openxml#1631).

Roll the table back before re-raising, so a failed call leaves the document
exactly as it was.

The regression test builds a real document, calls `add_table()` with an
undefined style and asserts no table is left in `document.tables`. It is a
module-level function named `it_...` because `python_functions` in
`pyproject.toml` only collects that prefix.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Trying to add a table with an absent style creates the table but does not return it

1 participant