Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a string with a namedtuple

Tags:

python

I'm wondering if there is a way to use the variablelist of a namedtuple to format a string efficiently like so:

TestResult = collections.namedtuple('TestResults', 'creation_time filter_time total_time')

test = TestResult(1, 2, 3)
string_to_format = '{creation_time}, {filter_time}, {total_time}'.format(test)

instead of just writing:

string_to_format = '{}, {}, {}'.format(test.creation_time, test.filter_time, test.total_time)

If there is a way to do this, would it be considered pythonic?

Thank you for your answers

like image 314
kachink Avatar asked Jun 02 '18 09:06

kachink


2 Answers

You can do:

>>> string_to_format = '{0.creation_time}, {0.filter_time}, {0.total_time}'.format(test)
>>> string_to_format
'1, 2, 3'

Is this Pythonic? I don't know but it does two things that are considered Pythonic: 1. Don't repeat yourself! (test occurs only once) and 2. Be explicit! (the names in a namedtuple are there to be used)

like image 75
Paul Panzer Avatar answered Sep 20 '22 14:09

Paul Panzer


You can use the _asdict() method to turn your namedtuple into a dict, and then unpack it with the ** splat operator:

test = TestResult(1, 2, 3)

string_to_format = '{creation_time}, {filter_time}, {total_time}'
print(string_to_format.format(**test._asdict()))
# output: 1, 2, 3
like image 33
Aran-Fey Avatar answered Sep 20 '22 14:09

Aran-Fey