Created
January 17, 2012 22:51
-
-
Save jdrake/1629587 to your computer and use it in GitHub Desktop.
Print list of objects to stdout
This file contains hidden or 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
from collections import Counter | |
def table(data, fields, user_config={}, debug=False): | |
"""Nicely formatted table, for printing to stdout | |
Required: | |
@param data: list, objects instances | |
@param fields: list, object properties/fields to display | |
Optional: | |
@param user_config: dict, overriding auto config: | |
specify "field" => {..options..}, e.g. | |
options = { | |
'player_in': { | |
'max_length': 10, | |
'align': 'center', | |
'format': fn_name | |
} | |
} | |
@param debug: bool, show steps | |
""" | |
# Set default config | |
config = { | |
field: { | |
'max_length': None, | |
'align': None, | |
'format': getattr(builtin, 'unicode'), | |
} for field in fields | |
} | |
# Merge configs | |
for field in fields: | |
# Override from user | |
if field in user_config: | |
config[field].update(user_config[field]) | |
# Max width of field value in chars | |
if not config[field]['max_length']: | |
config[field]['max_length'] = max( | |
[len(field)] + | |
[len(config[field]['format'](getattr(row, field))) | |
for row in data] | |
) | |
# Alignment based on most common var type | |
if not config[field]['align']: | |
types = [type(config[field]['format'](getattr(row, field))) for row in data] | |
groups = Counter(types) | |
data_type = groups.most_common(1)[0][0] | |
config[field]['align'] = "rjust" if data_type in [int, float] else "ljust" | |
# Output strings | |
trs = [] | |
data.insert(0, fields) # throw fields list back in | |
for i, row in enumerate(data): | |
tds = [] | |
for field in fields: | |
value = field.upper() if i==0 else config[field]['format'](getattr(row, field)) | |
max_length = config[field]['max_length'] | |
align = "center" if i==0 else config[field]['align'] | |
td = getattr(unicode(value)[:max_length], align)(max_length) | |
tds.append(td) | |
trs.append(' '.join(tds)) | |
# Combine rows, add line | |
total_width = sum([config[field]['max_length'] for field in fields]) + 2*(len(fields)-1) # add space at end for the col separators | |
table = trs[:1] + ["-"*total_width] + trs[1:] | |
return '\n' + '\n'.join(table) + '\n' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment