|
| 1 | +# tableformat.py |
| 2 | + |
| 3 | +class TableFormatter: |
| 4 | + def headings(self, headers): |
| 5 | + """ |
| 6 | + Emit the table headings. |
| 7 | + """ |
| 8 | + raise NotImplementedError() |
| 9 | + |
| 10 | + def row(self, rowdata): |
| 11 | + """ |
| 12 | + Emit a single row of table data. |
| 13 | + """ |
| 14 | + raise NotImplementedError() |
| 15 | + |
| 16 | + |
| 17 | +class TextTableFormatter(TableFormatter): |
| 18 | + """ |
| 19 | + Emit a table in plain-text format |
| 20 | + """ |
| 21 | + def headings(self, headers): |
| 22 | + for h in headers: |
| 23 | + print(f'{h:>10s}', end=' ') |
| 24 | + print() |
| 25 | + print(('-' * 10 + ' ') * len(headers)) |
| 26 | + |
| 27 | + def row(self, row_data): |
| 28 | + for column in row_data: |
| 29 | + print(f'{column:>10}', end=' ') |
| 30 | + print() |
| 31 | + |
| 32 | + |
| 33 | +class CSVTableFormatter(TableFormatter): |
| 34 | + """ |
| 35 | + Output portfolio data in CSV format. |
| 36 | + """ |
| 37 | + def headings(self, headers): |
| 38 | + print(','.join(headers)) |
| 39 | + |
| 40 | + def row(self, row_data): |
| 41 | + print(','.join(row_data)) |
| 42 | + |
| 43 | +class HTMLTableFormatter(TableFormatter): |
| 44 | + """ |
| 45 | + Output portfolio data in HTML format. |
| 46 | + """ |
| 47 | + def print_row(self, data, wrapper='td'): |
| 48 | + print('<tr>', end='') |
| 49 | + for column in data: |
| 50 | + print(f'<{wrapper}>{column}</{wrapper}>', end='') |
| 51 | + print('</tr>') |
| 52 | + |
| 53 | + def headings(self, headers): |
| 54 | + self.print_row(headers, 'th') |
| 55 | + |
| 56 | + def row(self, row_data): |
| 57 | + self.print_row(row_data) |
| 58 | + |
| 59 | + |
| 60 | +def create_formatter(name): |
| 61 | + if name == 'txt': |
| 62 | + formatter = TextTableFormatter() |
| 63 | + elif name == 'csv': |
| 64 | + formatter = CSVTableFormatter() |
| 65 | + elif name == 'html': |
| 66 | + formatter = HTMLTableFormatter() |
| 67 | + else: |
| 68 | + raise FormatError(f'Unknown table format {name}') |
| 69 | + return formatter |
| 70 | + |
| 71 | + |
| 72 | +def print_table(portfolio, columns, formatter): |
| 73 | + formatter.headings(columns) |
| 74 | + for holding in portfolio: |
| 75 | + line = [getattr(holding, column) for column in columns] |
| 76 | + formatter.row(line) |
| 77 | + |
| 78 | + |
| 79 | +class FormatError(Exception): |
| 80 | + pass |
0 commit comments