Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit bdf4c36

Browse files
committed
fix: python-openxml#455 Increment max-id, don't fill gaps
While this may not work in all cases, it is less ugly than arbitrarily boosting the id value as suggested. A general-case fix will have to wait for access to headers and footers. It definitely reduces the likelihood of a collision.
1 parent e51ae26 commit bdf4c36

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

docx/parts/document.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,16 +96,17 @@ def new_pic_inline(self, image_descriptor, width, height):
9696

9797
@property
9898
def next_id(self):
99-
"""
100-
The next available positive integer id value in this document. Gaps
101-
in id sequence are filled. The id attribute value is unique in the
102-
document, without regard to the element type it appears on.
99+
"""Next available positive integer id value in this document.
100+
101+
Calculated by incrementing maximum existing id value. Gaps in the
102+
existing id sequence are not filled. The id attribute value is unique
103+
in the document, without regard to the element type it appears on.
103104
"""
104105
id_str_lst = self._element.xpath('//@id')
105106
used_ids = [int(id_str) for id_str in id_str_lst if id_str.isdigit()]
106-
for n in range(1, len(used_ids)+2):
107-
if n not in used_ids:
108-
return n
107+
if not used_ids:
108+
return 1
109+
return max(used_ids) + 1
109110

110111
@lazyproperty
111112
def numbering_part(self):

tests/parts/test_document.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# encoding: utf-8
22

3-
"""
4-
Test suite for the docx.parts.document module
5-
"""
3+
"""Test suite for the docx.parts.document module"""
64

75
from __future__ import absolute_import, print_function, unicode_literals
86

@@ -198,8 +196,15 @@ def inline_shapes_fixture(self, request, InlineShapes_):
198196
return document, InlineShapes_, body_elm
199197

200198
@pytest.fixture(params=[
201-
((), 1), ((1,), 2), ((2,), 1), ((1, 2, 3), 4), ((1, 2, 4), 3),
202-
((0, 0), 1), ((0, 0, 1, 3), 2), (('foo', 1, 2), 3), ((1, 'bar'), 2)
199+
((), 1),
200+
((1,), 2),
201+
((2,), 3),
202+
((1, 2, 3), 4),
203+
((1, 2, 4), 5),
204+
((0, 0), 1),
205+
((0, 0, 1, 3), 4),
206+
(('foo', 1, 2), 3),
207+
((1, 'bar'), 2)
203208
])
204209
def next_id_fixture(self, request):
205210
existing_ids, expected_id = request.param

0 commit comments

Comments
 (0)