NiBabel

Access a cacophony of neuro-imaging file formats

Previous topic

nibabel.volumeutils.make_dt_codes

Next topic

nibabel.volumeutils.rec2dict

This Page

Reggie -- the one

nibabel.volumeutils.pretty_mapping

nibabel.volumeutils.pretty_mapping(mapping, getterfunc=None)

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

implementing iterator returning keys and .items()

getterfunc : None or callable

callable taking two arguments, obj and key where obj is the passed mapping. If None, just use lambda obj, key: obj[key]

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