Text based table. The number of columns and the width of each column is automatically calculated.
| 1070 | |
| 1071 | |
| 1072 | class Table(object): |
| 1073 | """ |
| 1074 | Text based table. The number of columns and the width of each column |
| 1075 | is automatically calculated. |
| 1076 | """ |
| 1077 | |
| 1078 | def __init__(self, sep=" "): |
| 1079 | """ |
| 1080 | @type sep: str |
| 1081 | @param sep: Separator between cells in each row. |
| 1082 | """ |
| 1083 | self.__cols = list() |
| 1084 | self.__width = list() |
| 1085 | self.__sep = sep |
| 1086 | |
| 1087 | def addRow(self, *row): |
| 1088 | """ |
| 1089 | Add a row to the table. All items are converted to strings. |
| 1090 | |
| 1091 | @type row: tuple |
| 1092 | @keyword row: Each argument is a cell in the table. |
| 1093 | """ |
| 1094 | row = [str(item) for item in row] |
| 1095 | len_row = [len(item) for item in row] |
| 1096 | width = self.__width |
| 1097 | len_old = len(width) |
| 1098 | len_new = len(row) |
| 1099 | known = min(len_old, len_new) |
| 1100 | missing = len_new - len_old |
| 1101 | if missing > 0: |
| 1102 | width.extend(len_row[-missing:]) |
| 1103 | elif missing < 0: |
| 1104 | len_row.extend([0] * (-missing)) |
| 1105 | self.__width = [max(width[i], len_row[i]) for i in compat.xrange(len(len_row))] |
| 1106 | self.__cols.append(row) |
| 1107 | |
| 1108 | def justify(self, column, direction): |
| 1109 | """ |
| 1110 | Make the text in a column left or right justified. |
| 1111 | |
| 1112 | @type column: int |
| 1113 | @param column: Index of the column. |
| 1114 | |
| 1115 | @type direction: int |
| 1116 | @param direction: |
| 1117 | C{-1} to justify left, |
| 1118 | C{1} to justify right. |
| 1119 | |
| 1120 | @raise IndexError: Bad column index. |
| 1121 | @raise ValueError: Bad direction value. |
| 1122 | """ |
| 1123 | if direction == -1: |
| 1124 | self.__width[column] = abs(self.__width[column]) |
| 1125 | elif direction == 1: |
| 1126 | self.__width[column] = -abs(self.__width[column]) |
| 1127 | else: |
| 1128 | raise ValueError("Bad direction value.") |
| 1129 |
no outgoing calls
no test coverage detected