| 1 |
# -*- coding: utf-8 -*- |
| 2 |
"""A generic tabular data output formatter interface.""" |
| 3 |
|
| 4 |
from __future__ import unicode_literals |
| 5 |
from collections import namedtuple |
| 6 |
|
| 7 |
from cli_helpers.compat import ( |
| 8 |
text_type, |
| 9 |
binary_type, |
| 10 |
int_types, |
| 11 |
float_types, |
| 12 |
zip_longest, |
| 13 |
) |
| 14 |
from cli_helpers.utils import unique_items |
| 15 |
from . import ( |
| 16 |
delimited_output_adapter, |
| 17 |
vertical_table_adapter, |
| 18 |
tabulate_adapter, |
| 19 |
tsv_output_adapter, |
| 20 |
json_output_adapter, |
| 21 |
) |
| 22 |
from decimal import Decimal |
| 23 |
|
| 24 |
import itertools |
| 25 |
|
| 26 |
MISSING_VALUE = "<null>" |
| 27 |
MAX_FIELD_WIDTH = 500 |
| 28 |
|
| 29 |
TYPES = { |
| 30 |
type(None): 0, |
| 31 |
bool: 1, |
| 32 |
int: 2, |
| 33 |
float: 3, |
| 34 |
Decimal: 3, |
| 35 |
binary_type: 4, |
| 36 |
text_type: 5, |
| 37 |
} |
| 38 |
|
| 39 |
OutputFormatHandler = namedtuple( |
| 40 |
"OutputFormatHandler", "format_name preprocessors formatter formatter_args" |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
class TabularOutputFormatter(object): |
| 45 |
"""An interface to various tabular data formatting libraries. |
| 46 |
|
| 47 |
The formatting libraries supported include: |
| 48 |
- `tabulate <https://bitbucket.org/astanin/python-tabulate>`_ |
| 49 |
- `terminaltables <https://robpol86.github.io/terminaltables/>`_ |
| 50 |
- a CLI Helper vertical table layout |
| 51 |
- delimited formats (CSV and TSV) |
| 52 |
|
| 53 |
:param str format_name: An optional, default format name. |
| 54 |
|
| 55 |
Usage:: |
| 56 |
|
| 57 |
>>> from cli_helpers.tabular_output import TabularOutputFormatter |
| 58 |
>>> formatter = TabularOutputFormatter(format_name='simple') |
| 59 |
>>> data = ((1, 87), (2, 80), (3, 79)) |
| 60 |
>>> headers = ('day', 'temperature') |
| 61 |
>>> print(formatter.format_output(data, headers)) |
| 62 |
day temperature |
| 63 |
----- ------------- |
| 64 |
1 87 |
| 65 |
2 80 |
| 66 |
3 79 |
| 67 |
|
| 68 |
You can use any :term:`iterable` for the data or headers:: |
| 69 |
|
| 70 |
>>> data = enumerate(('87', '80', '79'), 1) |
| 71 |
>>> print(formatter.format_output(data, headers)) |
| 72 |
day temperature |
| 73 |
----- ------------- |
| 74 |
1 87 |
| 75 |
2 80 |
| 76 |
3 79 |
| 77 |
|
| 78 |
""" |
| 79 |
|
| 80 |
_output_formats = {} |
| 81 |
|
| 82 |
def __init__(self, format_name=None): |
| 83 |
"""Set the default *format_name*.""" |
| 84 |
self._format_name = None |
| 85 |
|
| 86 |
if format_name: |
| 87 |
self.format_name = format_name |
| 88 |
|
| 89 |
@property |
| 90 |
def format_name(self): |
| 91 |
"""The current format name. |
| 92 |
|
| 93 |
This value must be in :data:`supported_formats`. |
| 94 |
|
| 95 |
""" |
| 96 |
return self._format_name |
| 97 |
|
| 98 |
@format_name.setter |
| 99 |
def format_name(self, format_name): |
| 100 |
"""Set the default format name. |
| 101 |
|
| 102 |
:param str format_name: The display format name. |
| 103 |
:raises ValueError: if the format is not recognized. |
| 104 |
|
| 105 |
""" |
| 106 |
if format_name in self.supported_formats: |
| 107 |
self._format_name = format_name |
| 108 |
else: |
| 109 |
raise ValueError('unrecognized format_name "{}"'.format(format_name)) |
| 110 |
|
| 111 |
@property |
| 112 |
def supported_formats(self): |
| 113 |
"""The names of the supported output formats in a :class:`tuple`.""" |
| 114 |
return tuple(self._output_formats.keys()) |
| 115 |
|
| 116 |
@classmethod |
| 117 |
def register_new_formatter( |
| 118 |
cls, format_name, handler, preprocessors=(), kwargs=None |
| 119 |
): |
| 120 |
"""Register a new output formatter. |
| 121 |
|
| 122 |
:param str format_name: The name of the format. |
| 123 |
:param callable handler: The function that formats the data. |
| 124 |
:param tuple preprocessors: The preprocessors to call before |
| 125 |
formatting. |
| 126 |
:param dict kwargs: Keys/values for keyword argument defaults. |
| 127 |
|
| 128 |
""" |
| 129 |
cls._output_formats[format_name] = OutputFormatHandler( |
| 130 |
format_name, preprocessors, handler, kwargs or {} |
| 131 |
) |
| 132 |
|
| 133 |
def format_output( |
| 134 |
self, |
| 135 |
data, |
| 136 |
headers, |
| 137 |
format_name=None, |
| 138 |
preprocessors=(), |
| 139 |
column_types=None, |
| 140 |
**kwargs |
| 141 |
): |
| 142 |
r"""Format the headers and data using a specific formatter. |
| 143 |
|
| 144 |
*format_name* must be a supported formatter (see |
| 145 |
:attr:`supported_formats`). |
| 146 |
|
| 147 |
:param iterable data: An :term:`iterable` (e.g. list) of rows. |
| 148 |
:param iterable headers: The column headers. |
| 149 |
:param str format_name: The display format to use (optional, if the |
| 150 |
:class:`TabularOutputFormatter` object has a default format set). |
| 151 |
:param tuple preprocessors: Additional preprocessors to call before |
| 152 |
any formatter preprocessors. |
| 153 |
:param \*\*kwargs: Optional arguments for the formatter. |
| 154 |
:return: The formatted data. |
| 155 |
:rtype: str |
| 156 |
:raises ValueError: If the *format_name* is not recognized. |
| 157 |
|
| 158 |
""" |
| 159 |
format_name = format_name or self._format_name |
| 160 |
if format_name not in self.supported_formats: |
| 161 |
raise ValueError('unrecognized format "{}"'.format(format_name)) |
| 162 |
|
| 163 |
(_, _preprocessors, formatter, fkwargs) = self._output_formats[format_name] |
| 164 |
fkwargs.update(kwargs) |
| 165 |
if column_types is None: |
| 166 |
data = list(data) |
| 167 |
column_types = self._get_column_types(data) |
| 168 |
for f in unique_items(preprocessors + _preprocessors): |
| 169 |
data, headers = f(data, headers, column_types=column_types, **fkwargs) |
| 170 |
return formatter(list(data), headers, column_types=column_types, **fkwargs) |
| 171 |
|
| 172 |
def _get_column_types(self, data): |
| 173 |
"""Get a list of the data types for each column in *data*.""" |
| 174 |
columns = list(zip_longest(*data)) |
| 175 |
return [self._get_column_type(column) for column in columns] |
| 176 |
|
| 177 |
def _get_column_type(self, column): |
| 178 |
"""Get the most generic data type for iterable *column*.""" |
| 179 |
type_values = [TYPES[self._get_type(v)] for v in column] |
| 180 |
inverse_types = {v: k for k, v in TYPES.items()} |
| 181 |
return inverse_types[max(type_values)] |
| 182 |
|
| 183 |
def _get_type(self, value): |
| 184 |
"""Get the data type for *value*.""" |
| 185 |
if value is None: |
| 186 |
return type(None) |
| 187 |
elif type(value) in int_types: |
| 188 |
return int |
| 189 |
elif type(value) in float_types: |
| 190 |
return float |
| 191 |
elif isinstance(value, binary_type): |
| 192 |
return binary_type |
| 193 |
else: |
| 194 |
return text_type |
| 195 |
|
| 196 |
|
| 197 |
def format_output(data, headers, format_name, **kwargs): |
| 198 |
r"""Format output using *format_name*. |
| 199 |
|
| 200 |
This is a wrapper around the :class:`TabularOutputFormatter` class. |
| 201 |
|
| 202 |
:param iterable data: An :term:`iterable` (e.g. list) of rows. |
| 203 |
:param iterable headers: The column headers. |
| 204 |
:param str format_name: The display format to use. |
| 205 |
:param \*\*kwargs: Optional arguments for the formatter. |
| 206 |
:return: The formatted data. |
| 207 |
:rtype: str |
| 208 |
|
| 209 |
""" |
| 210 |
formatter = TabularOutputFormatter(format_name=format_name) |
| 211 |
return formatter.format_output(data, headers, **kwargs) |
| 212 |
|
| 213 |
|
| 214 |
for vertical_format in vertical_table_adapter.supported_formats: |
| 215 |
TabularOutputFormatter.register_new_formatter( |
| 216 |
vertical_format, |
| 217 |
vertical_table_adapter.adapter, |
| 218 |
vertical_table_adapter.preprocessors, |
| 219 |
{ |
| 220 |
"table_format": vertical_format, |
| 221 |
"missing_value": MISSING_VALUE, |
| 222 |
"max_field_width": None, |
| 223 |
}, |
| 224 |
) |
| 225 |
|
| 226 |
for delimited_format in delimited_output_adapter.supported_formats: |
| 227 |
TabularOutputFormatter.register_new_formatter( |
| 228 |
delimited_format, |
| 229 |
delimited_output_adapter.adapter, |
| 230 |
delimited_output_adapter.preprocessors, |
| 231 |
{ |
| 232 |
"table_format": delimited_format, |
| 233 |
"missing_value": "", |
| 234 |
"max_field_width": None, |
| 235 |
}, |
| 236 |
) |
| 237 |
|
| 238 |
for tabulate_format in tabulate_adapter.supported_formats: |
| 239 |
TabularOutputFormatter.register_new_formatter( |
| 240 |
tabulate_format, |
| 241 |
tabulate_adapter.adapter, |
| 242 |
tabulate_adapter.get_preprocessors(tabulate_format), |
| 243 |
{ |
| 244 |
"table_format": tabulate_format, |
| 245 |
"missing_value": MISSING_VALUE, |
| 246 |
"max_field_width": MAX_FIELD_WIDTH, |
| 247 |
}, |
| 248 |
), |
| 249 |
|
| 250 |
for tsv_format in tsv_output_adapter.supported_formats: |
| 251 |
TabularOutputFormatter.register_new_formatter( |
| 252 |
tsv_format, |
| 253 |
tsv_output_adapter.adapter, |
| 254 |
tsv_output_adapter.preprocessors, |
| 255 |
{"table_format": tsv_format, "missing_value": "", "max_field_width": None}, |
| 256 |
) |
| 257 |
|
| 258 |
for json_format in json_output_adapter.supported_formats: |
| 259 |
TabularOutputFormatter.register_new_formatter( |
| 260 |
json_format, |
| 261 |
json_output_adapter.adapter, |
| 262 |
json_output_adapter.preprocessors, |
| 263 |
{ |
| 264 |
"table_format": json_format, |
| 265 |
"max_field_width": None, |
| 266 |
}, |
| 267 |
) |