-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtableful_utils.py
81 lines (64 loc) · 2.12 KB
/
tableful_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from itertools import zip_longest
def _GetDictHeaders(dictionary):
'''
Calculate headers for the table based on dict keys.
Returns the headers as a tuple so that number of columns
and their header can be determined.
'''
if isinstance(dictionary, dict):
return tuple(key for key in dictionary)
else:
return None
def _GetIterableHeaders(iterable):
'''
Get headers out of an iterable.
Headers are determined by the first item of the
iterable. The first value must be an iterable.
If the item isn't an iterable, it returns none.
'''
try:
return tuple(iterable[0])
except:
return None
def _GetDictRows(dictionary):
'''
Grabs the columns out of a dict and turns them into rowss.
'''
try:
values = (v for v in dictionary.values())
columns = tuple(zip_longest(*values, fillvalue=''))
return columns
except AttributeError:
return None
def _GetIterableRows(iterable, *, embeddedHeaders=False):
'''
Gets the rows from the iterable.
'''
if isinstance(iterable, dict):
return None
try:
if embeddedHeaders:
iterable = iterable[1:]
return tuple(zip(*zip_longest(*iterable, fillvalue=''))) # by zipping we can ensure all cols are filled
except:
return None
def _GetColumnWidths(headers, rows):
'''
Calculate the width of each column.
'''
headers = (len(str(header)) for header in headers)
columns = zip(*rows)
columnLengths = []
for column in columns:
currentMax = max(column, key=lambda x: len(str(x)))
columnLengths.append(len(str(currentMax))) # convert to str so we can grab len
return tuple(max(length) for length in zip(headers, columnLengths))
def _GetDivider(columMaxes, *, corners='+', divider='-'):
'''
Builds a divider based on the length of each column
'''
dashes = (divider * length for length in columMaxes)
return "{0}{1}{0}".format(corners, corners.join(dashes))
def _BuildCellString(text, width):
template = "{{: ^{}}}".format(width)
return template.format(text)