From 26dd4d81f08ad75d8260d9c2518d1b530746ea06 Mon Sep 17 00:00:00 2001 From: Niru Maheswaranathan Date: Tue, 23 May 2017 13:48:45 -0700 Subject: [PATCH] Adds Table() contextmanager for easy dynamic tables :cherry_blossom: --- tableprint.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tableprint.py b/tableprint.py index 5870e53..ee25646 100644 --- a/tableprint.py +++ b/tableprint.py @@ -14,6 +14,7 @@ from __future__ import print_function, unicode_literals from six import string_types from collections import namedtuple from numbers import Number +from contextlib import ContextDecorator import sys import re import numpy as np @@ -68,6 +69,22 @@ WIDTH = 11 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): """Print a table with the given data