Make pretty string from mapping
Adjusts text column to print values on basis of longest key. Probably only sensible if keys are mainly strings.
You can pass in a callable that does clever things to get the values out of the mapping, given the names. By default, we just use __getitem__
Parameters : | mapping : mapping
getterfunc : None or callable
|
---|---|
Returns : | str : string |
Examples
>>> d = {'a key': 'a value'}
>>> print pretty_mapping(d)
a key : a value
>>> class C(object): # to control ordering, show get_ method
... def __iter__(self):
... return iter(('short_field','longer_field'))
... def __getitem__(self, key):
... if key == 'short_field':
... return 0
... if key == 'longer_field':
... return 'str'
... def get_longer_field(self):
... return 'method string'
>>> def getter(obj, key):
... # Look for any 'get_<name>' methods
... try:
... return obj.__getattribute__('get_' + key)()
... except AttributeError:
... return obj[key]
>>> print pretty_mapping(C(), getter)
short_field : 0
longer_field : method string