Adds Table() contextmanager for easy dynamic tables 🌸

This commit is contained in:
Niru Maheswaranathan
2017-05-23 13:48:45 -07:00
parent cb7c1d27f4
commit 26dd4d81f0

View File

@@ -14,6 +14,7 @@ from __future__ import print_function, unicode_literals
from six import string_types from six import string_types
from collections import namedtuple from collections import namedtuple
from numbers import Number from numbers import Number
from contextlib import ContextDecorator
import sys import sys
import re import re
import numpy as np import numpy as np
@@ -68,6 +69,22 @@ WIDTH = 11
FMT = '5g' FMT = '5g'
class Table(ContextDecorator):
def __init__(self, headers, width=WIDTH, style=STYLE, add_hr=True):
self.headers = header(headers, width=WIDTH, style=STYLE, add_hr=add_hr)
self.bottom = bottom(len(headers), width=WIDTH, style=STYLE)
def __call__(self, data):
print(row(data), flush=True)
def __enter__(self):
print(self.headers, flush=True)
return self
def __exit__(self, *exc):
print(self.bottom, flush=True)
def table(data, headers=None, format_spec=FMT, width=WIDTH, style=STYLE, out=sys.stdout): def table(data, headers=None, format_spec=FMT, width=WIDTH, style=STYLE, out=sys.stdout):
"""Print a table with the given data """Print a table with the given data