Skip to content

Commit 378d206

Browse files
author
Steve Canny
committed
tbl: enable sliced access to _Rows
1 parent 68e52c8 commit 378d206

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

docx/table.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -370,8 +370,8 @@ def _index(self):
370370

371371
class _Rows(Parented):
372372
"""
373-
Sequence of |_Row| instances corresponding to the rows in a table.
374-
Supports ``len()``, iteration and indexed access.
373+
Sequence of |_Row| objects corresponding to the rows in a table.
374+
Supports ``len()``, iteration, indexed access, and slicing.
375375
"""
376376
def __init__(self, tbl, parent):
377377
super(_Rows, self).__init__(parent)
@@ -381,12 +381,7 @@ def __getitem__(self, idx):
381381
"""
382382
Provide indexed access, (e.g. 'rows[0]')
383383
"""
384-
try:
385-
tr = self._tbl.tr_lst[idx]
386-
except IndexError:
387-
msg = "row index [%d] out of range" % idx
388-
raise IndexError(msg)
389-
return _Row(tr, self)
384+
return list(self)[idx]
390385

391386
def __iter__(self):
392387
return (_Row(tr, self) for tr in self._tbl.tr_lst)

tests/test_table.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,15 @@ def it_provides_indexed_access_to_rows(self, rows_fixture):
678678
row = rows[idx]
679679
assert isinstance(row, _Row)
680680

681+
def it_provides_sliced_access_to_rows(self, slice_fixture):
682+
rows, start, end, expected_count = slice_fixture
683+
slice_of_rows = rows[start:end]
684+
assert len(slice_of_rows) == expected_count
685+
tr_lst = rows._tbl.tr_lst
686+
for idx, row in enumerate(slice_of_rows):
687+
assert tr_lst.index(row._tr) == start + idx
688+
assert isinstance(row, _Row)
689+
681690
def it_raises_on_indexed_access_out_of_range(self, rows_fixture):
682691
rows, row_count = rows_fixture
683692
with pytest.raises(IndexError):
@@ -700,6 +709,16 @@ def rows_fixture(self):
700709
rows = _Rows(tbl, None)
701710
return rows, row_count
702711

712+
@pytest.fixture(params=[
713+
(3, 1, 3, 2),
714+
(3, 0, -1, 2),
715+
])
716+
def slice_fixture(self, request):
717+
row_count, start, end, expected_count = request.param
718+
tbl = _tbl_bldr(rows=row_count, cols=2).element
719+
rows = _Rows(tbl, None)
720+
return rows, start, end, expected_count
721+
703722
@pytest.fixture
704723
def table_fixture(self, table_):
705724
rows = _Rows(None, table_)

0 commit comments

Comments
 (0)