Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namedtuple formatted/pretty print in Python

Having trouble printing a namedtuple:

Info = namedtuple('Info', ['type', 'value', 'x', 'y'])

so that the values are aligned and with space(padding) between them, for example like so:

Info( type='AAA',    value=80000,   x=16.4,   y=164.2 )
Info( type='A',      value=78,      x=1.5,    y=11.3  )
Info( type='ABBCD',  value=554,     x=11.7,   y=10.1  )
Info( type='AFFG',   value=1263,    x=121.3,  y=12.8  )

Ideally, without the commas. I have tried pprint and tried printing using the _asdict with no success as suggested here. Same with the format which I could not make it to behave with named tuples. Any ideas or example codes?

like image 900
Yannis Avatar asked Mar 12 '23 15:03

Yannis


1 Answers

Here is my implementation of a pretty print for named tuples:

def prettyprint_namedtuple(namedtuple,field_spaces):
    assert len(field_spaces) == len(namedtuple._fields)
    string = "{0.__name__}( ".format(type(namedtuple))
    for f_n,f_v,f_s in zip(namedtuple._fields,namedtuple,field_spaces):
        string+= "{f_n}={f_v!r:<{f_s}}".format(f_n=f_n,f_v=f_v,f_s=f_s)
    return string+")"

gives the output I believe you were looking for:

a = Info( type='AAA',    value=80000,   x=16.4,   y=164.2 )
b = Info( type='A',      value=78,      x=1.5,    y=11.3  )
c = Info( type='ABBCD',  value=554,     x=11.7,   y=10.1  )
d = Info( type='AFFG',   value=1263,    x=121.3,  y=12.8  )

tups = [a,b,c,d]

for t in tups:
    print(prettyprint_namedtuple(t,(10, 9, 8, 6)))

output:

Info( type='AAA'     value=80000    x=16.4    y=164.2 )
Info( type='A'       value=78       x=1.5     y=11.3  )
Info( type='ABBCD'   value=554      x=11.7    y=10.1  )
Info( type='AFFG'    value=1263     x=121.3   y=12.8  )
like image 196
Tadhg McDonald-Jensen Avatar answered Mar 15 '23 22:03

Tadhg McDonald-Jensen