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
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With