kachink
kachink

Reputation: 109

Formatting a string with a namedtuple

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

Upvotes: 9

Views: 3466

Answers (4)

Paul Panzer
Paul Panzer

Reputation: 53029

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)

Upvotes: 12

Norrius
Norrius

Reputation: 7920

You can convert it to a dictionary and use it as the parameters for format:

test = TestResult(1, 2, 3)
s = '{creation_time}, {filter_time}, {total_time}'.format(**test._asdict())
print(s)  # 1, 2, 3

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43146

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

Upvotes: 6

DeepSpace
DeepSpace

Reputation: 81594

Your attempt was close. You should change

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

to

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

Upvotes: 1

Related Questions