diff --git a/tablib/core.py b/tablib/core.py index 1bdd49f..80f4418 100644 --- a/tablib/core.py +++ b/tablib/core.py @@ -223,6 +223,23 @@ class Dataset(object): except AttributeError: return '' + def __unicode__(self): + result = [self.__headers] + + result.extend(map(unicode, row) for row in self._data) + + # here, we calculate max width for each column + lens = (map(len, row) for row in result) + field_lens = map(max, zip(*lens)) + + # delimiter between header and data + result.insert(1, [u'-' * length for length in field_lens]) + + format_string = u'|'.join(u'{%s:%s}' % item for item in enumerate(field_lens)) + + return u'\n'.join(format_string.format(*row) for row in result) + + # --------- # Internals diff --git a/test_tablib.py b/test_tablib.py index 5455c28..0bfb417 100755 --- a/test_tablib.py +++ b/test_tablib.py @@ -649,6 +649,22 @@ class TablibTestCase(unittest.TestCase): self.assertEquals(self.founders[orig_target_header], data[target_header]) + def test_unicode_renders_markdown_table(self): + # add another entry to test right field width for + # integer + self.founders.append(('Old', 'Man', 100500)) + + self.assertEquals( + u""" +first_name|last_name |gpa +----------|----------|------ +John |Adams |90 +George |Washington|67 +Thomas |Jefferson |50 +Old |Man |100500 +""".strip(), + unicode(self.founders) + ) if __name__ == '__main__':