Skip to content

Commit 85be65c

Browse files
author
Steve Canny
committed
shp: add InlineShapes.__iter__()
1 parent c376fb9 commit 85be65c

3 files changed

Lines changed: 22 additions & 4 deletions

File tree

docx/parts.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,9 @@ class InlineShape(object):
104104
Proxy for an ``<wp:inline>`` element, representing the container for an
105105
inline graphical object.
106106
"""
107+
def __init__(self, inline):
108+
super(InlineShape, self).__init__()
109+
self._inline = inline
107110

108111

109112
class InlineShapes(object):
@@ -115,8 +118,14 @@ def __init__(self, body_elm):
115118
super(InlineShapes, self).__init__()
116119
self._body = body_elm
117120

121+
def __iter__(self):
122+
return (InlineShape(inline) for inline in self._inline_lst)
123+
118124
def __len__(self):
125+
return len(self._inline_lst)
126+
127+
@property
128+
def _inline_lst(self):
119129
body = self._body
120130
xpath = './w:p/w:r/w:drawing/wp:inline'
121-
inline_elms = body.xpath(xpath, namespaces=nsmap)
122-
return len(inline_elms)
131+
return body.xpath(xpath, namespaces=nsmap)

features/steps/shape.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def given_a_document_containing_two_inline_shapes(context):
2626
def given_inline_shape_collection_containing_two_shapes(context):
2727
docx_path = test_docx('shp-inline-shape-access')
2828
document = Document(docx_path)
29-
context.inline_shapes = document.body.inline_shapes
29+
context.inline_shapes = document.inline_shapes
3030

3131

3232
# then =====================================================

tests/test_parts.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from mock import Mock
1212

1313
from docx.oxml.parts import CT_Document
14-
from docx.parts import _Body, _Document, InlineShapes
14+
from docx.parts import _Body, _Document, InlineShape, InlineShapes
1515
from docx.table import Table
1616
from docx.text import Paragraph
1717

@@ -264,6 +264,15 @@ def it_knows_how_many_inline_shapes_it_contains(
264264
print(inline_shapes._body.xml)
265265
assert len(inline_shapes) == inline_shape_count
266266

267+
def it_can_iterate_over_its_InlineShape_instances(
268+
self, inline_shapes_fixture):
269+
inline_shapes, inline_shape_count = inline_shapes_fixture
270+
actual_count = 0
271+
for inline_shape in inline_shapes:
272+
assert isinstance(inline_shape, InlineShape)
273+
actual_count += 1
274+
assert actual_count == inline_shape_count
275+
267276
# fixtures -------------------------------------------------------
268277

269278
@pytest.fixture

0 commit comments

Comments
 (0)