Created
April 19, 2019 20:07
-
-
Save algmyr/0f43a873818377e8b0a6539d177664b3 to your computer and use it in GitHub Desktop.
Python table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Content: | |
def __init__(self, *args): | |
self.data = args | |
def sizes(self): | |
return [len(str(x)) for x in self.data] | |
def __len__(self): | |
return len(self.data) | |
class Header(Content): | |
def layout(self, style): | |
return style.header.format(*self.data) | |
class Data(Content): | |
def layout(self, style): | |
return style.body.format(*self.data) | |
class Line: | |
def __init__(self, c='-'): | |
self.c = c | |
def layout(self, style): | |
fmt = style.header.replace(':', ':'+self.c) | |
return fmt.format(*['']*style.ncols) | |
class Style: | |
def __init__(self, body, header=None): | |
self._body = body | |
self._header = header or body | |
self.sizes = None | |
self.ncols = body.count('}') | |
def _pad(self, fmt): | |
i = 0 | |
S = [] | |
wascolon = False | |
lc = None | |
for c in fmt: | |
if lc == ':': | |
sz = str(self.sizes[i]) | |
i += 1 | |
if c in '<>^': | |
S.append(c + sz) | |
else: | |
S.append(sz + c) | |
else: | |
S.append(c) | |
lc = c | |
return ''.join(S) | |
def apply_padding(self, sizes): | |
self.sizes = sizes | |
self.body = self._pad(self._body) | |
self.header = self._pad(self._header) | |
class Table: | |
def __init__(self, style): | |
self.style = style | |
self.rows = [] | |
def append(self, row): | |
self.rows.append(row) | |
return t | |
__add__ = append | |
def __repr__(self): | |
S = [] | |
for row in self.rows: | |
if isinstance(row, Content): | |
S.append(row.sizes()) | |
maxlen = [max(s[i] for s in S) for i in range(self.style.ncols)] | |
self.style.apply_padding(maxlen) | |
R = [] | |
for row in self.rows: | |
R.append(row.layout(style)) | |
return '\n'.join(R) | |
__str__ = __repr__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment