variant of as_table (subtly different code) which has two additional parameters filter which is a list of fields which will be shown class_formatter a special method to format the outgoing data A general comment, the format selected for the output (a string where every data record is separated b
( obj: list[Any], class_formatter: str | Callable | None = None, # type: ignore[type-arg] filter_list: list[str] = [], capitalize: bool = False, )
| 87 | |
| 88 | |
| 89 | def as_table( |
| 90 | obj: list[Any], |
| 91 | class_formatter: str | Callable | None = None, # type: ignore[type-arg] |
| 92 | filter_list: list[str] = [], |
| 93 | capitalize: bool = False, |
| 94 | ) -> str: |
| 95 | """variant of as_table (subtly different code) which has two additional parameters |
| 96 | filter which is a list of fields which will be shown |
| 97 | class_formatter a special method to format the outgoing data |
| 98 | |
| 99 | A general comment, the format selected for the output (a string where every data record is separated by newline) |
| 100 | is for compatibility with a print statement |
| 101 | As_table_filter can be a drop in replacement for as_table |
| 102 | """ |
| 103 | raw_data = [_get_values(o, class_formatter, filter_list) for o in obj] |
| 104 | |
| 105 | # determine the maximum column size |
| 106 | column_width: dict[str, int] = {} |
| 107 | for o in raw_data: |
| 108 | for k, v in o.items(): |
| 109 | if not filter_list or k in filter_list: |
| 110 | column_width.setdefault(k, 0) |
| 111 | column_width[k] = max([column_width[k], len(str(v)), len(k)]) |
| 112 | |
| 113 | if not filter_list: |
| 114 | filter_list = list(column_width.keys()) |
| 115 | |
| 116 | # create the header lines |
| 117 | output = '' |
| 118 | key_list = [] |
| 119 | for key in filter_list: |
| 120 | width = column_width[key] |
| 121 | key = key.replace('!', '').replace('_', ' ') |
| 122 | |
| 123 | if capitalize: |
| 124 | key = key.capitalize() |
| 125 | |
| 126 | key_list.append(unicode_ljust(key, width)) |
| 127 | |
| 128 | output += ' | '.join(key_list) + '\n' |
| 129 | output += '-' * len(output) + '\n' |
| 130 | |
| 131 | # create the data lines |
| 132 | for record in raw_data: |
| 133 | obj_data = [] |
| 134 | for key in filter_list: |
| 135 | width = column_width.get(key, len(key)) |
| 136 | value = record.get(key, '') |
| 137 | |
| 138 | if '!' in key: |
| 139 | value = '*' * len(value) |
| 140 | |
| 141 | if isinstance(value, (int, float)) or (isinstance(value, str) and value.isnumeric()): |
| 142 | obj_data.append(unicode_rjust(str(value), width)) |
| 143 | else: |
| 144 | obj_data.append(unicode_ljust(str(value), width)) |
| 145 | |
| 146 | output += ' | '.join(obj_data) + '\n' |
no test coverage detected