diff --git a/CHANGELOG.md b/CHANGELOG.md index 4717cd3f..3d5f2482 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -70,6 +70,8 @@ - `apply_table_ops`의 같은 편집과 같은 규칙(한/글의 줄/칸 추가하기·지우기, 셀 나누기)을 따른다. 새 칸은 기준 칸의 글을 복제하고, `blank=True`면 그 칸 서식의 빈 문단 하나만 둔다. - 편집하면 표를 담은 문단의 줄 캐시를 지운다. 편집 전에 얻은 셀·행 객체는 표에 속하지 않으니 다시 얻는다. +- `doc.tables`를 번호로 꺼낼 수 있다: `doc.tables[0]`, `doc.tables[-1]`, `doc.tables[1:3]`(문서 순서, + `doc.tables.all[...]`와 같다). 범위 밖이면 `IndexError`. ### 고침 diff --git a/src/hwpx/_document/ns/tables.py b/src/hwpx/_document/ns/tables.py index 03d42e69..c199e070 100644 --- a/src/hwpx/_document/ns/tables.py +++ b/src/hwpx/_document/ns/tables.py @@ -11,7 +11,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Iterable, Mapping +from typing import TYPE_CHECKING, Iterable, Mapping, overload from ._base import _Namespace @@ -48,6 +48,20 @@ def __len__(self) -> int: def __iter__(self): return iter(self.all) + @overload + def __getitem__(self, index: int) -> "Table": ... + + @overload + def __getitem__(self, index: slice) -> list["Table"]: ... + + def __getitem__(self, index: int | slice) -> "Table | list[Table]": + """문서 순서의 ``index`` 번째 표(``doc.tables[0]``, ``doc.tables[-1]``, ``doc.tables[1:3]``). + + ``doc.tables.all[index]``와 같다. 범위 밖이면 ``IndexError``. + """ + + return self.all[index] + def map(self) -> "TableMapResult": """모든 표의 위치·모양·헤더 미리보기를 담은 간결 지도.""" diff --git a/tests/test_ns_tables.py b/tests/test_ns_tables.py index 320d3e83..b0242690 100644 --- a/tests/test_ns_tables.py +++ b/tests/test_ns_tables.py @@ -72,6 +72,27 @@ def test_all_and_len_agree_with_the_map(document: HwpxDocument) -> None: assert all(isinstance(table, model.Table) for table in document.tables) +def test_tables_index_and_slice_in_document_order(document: HwpxDocument) -> None: + document.add_table(2, 2) + document.add_table(3, 1) + document.add_table(1, 4) + shapes = [(t.row_count, t.column_count) for t in document.tables] + assert shapes == [(2, 2), (3, 1), (1, 4)] + assert (document.tables[0].row_count, document.tables[0].column_count) == (2, 2) + assert (document.tables[-1].row_count, document.tables[-1].column_count) == (1, 4) + assert [(t.row_count, t.column_count) for t in document.tables[1:]] == [(3, 1), (1, 4)] + assert all(isinstance(table, model.Table) for table in document.tables[:2]) + with pytest.raises(IndexError): + document.tables[3] + + +def test_an_indexed_table_edits_the_document(document: HwpxDocument) -> None: + document.add_table(2, 2) + document.tables[0].set_cell_text(0, 0, "첫 칸") + reopened = HwpxDocument.open(document.to_bytes()) + assert reopened.tables[0].cell(0, 0).text == "첫 칸" + + def test_find_cell_by_label_locates_the_neighbour(document: HwpxDocument) -> None: table = document.add_table(1, 2) table.set_cell_text(0, 0, "이름")