1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 class MismatchedRowLengthsException(Exception):
8 This exception is thrown when there is a mismatch between the number of items in a row,
9 and the number of headers defined.
15 class TableBuilder(object):
17 Helper class for building tables.
20 def __init__(self
, title
, widths
, header_rows
, headers
, indent
=0):
22 :param title: str - Title of the table
23 :param widths: list of str - Widths of each column of the table
24 :param header_rows: int - Number of header rows
25 :param headers: 2D list of str - Headers
26 :param indent: int - Number of spaces to indent table
28 if not isinstance(title
, str):
29 raise TypeError("TableBuilder attribute title must be a string.")
30 if not isinstance(widths
, list) or not isinstance(widths
[0], int):
31 raise TypeError("TableBuilder attribute widths must be a list of integers.")
32 if not isinstance(header_rows
, int):
33 raise TypeError("TableBuilder attribute header_rows must be an integer.")
35 not isinstance(headers
, list)
36 or not isinstance(headers
[0], list)
37 or not isinstance(headers
[0][0], str)
40 "TableBuilder attribute headers must be a two-dimensional list of strings."
42 if not isinstance(indent
, int):
43 raise TypeError("TableBuilder attribute indent must be an integer.")
47 self
.header_rows
= header_rows
48 self
.headers
= headers
49 self
.indent
= " " * indent
53 def _build_table(self
):
54 if len(self
.widths
) != len(self
.headers
[0]):
55 raise MismatchedRowLengthsException(
56 "Number of table headers must match number of column widths."
58 widths
= " ".join(map(str, self
.widths
))
60 f
"{self.indent}.. list-table:: **{self.title}**\n"
61 f
"{self.indent} :widths: {widths}\n"
62 f
"{self.indent} :header-rows: {self.header_rows}\n\n"
64 self
.add_rows(self
.headers
)
66 def add_rows(self
, rows
):
68 type(rows
) is not list
69 or type(rows
[0]) is not list
70 or type(rows
[0][0]) is not str
72 raise TypeError("add_rows() requires a two-dimensional list of strings.")
76 def add_row(self
, values
):
77 if len(values
) != len(self
.widths
):
78 raise MismatchedRowLengthsException(
79 "Number of items in a row must must number of columns defined."
81 for i
, val
in enumerate(values
):
83 self
.table
+= f
"{self.indent} * - **{val}**\n"
85 self
.table
+= f
"{self.indent} - {val}\n"
87 def finish_table(self
):