[Python-ideas] String interpolation again.
Eric Smith
eric at trueblade.com
Fri Jul 23 21:38:56 CEST 2010
On 7/23/10 3:26 PM, Dag Odenhall wrote:
>> In my code, '{bar}' and 'bar=bar' seems too verbose.
>> Your code is simple when the literal is short, but it is difficult to
>> check which variable
>> is inserted where when string is long.
>
> format = '...{short_descriptive_name}...'
> text = format.format(
> short_descriptive_name=long_cumbersome_variable_name,
> other_name=other_name,
> ...)
>
> Don't be afraid of more lines of code if it helps readability.
>
> You could also build a context dict:
>
> context = {}
> context['name'] = complicated_code_to_get_name()
> ...
> text = '...{name}...'.format(**context)
Or use:
text = '...{context.name}...'.format(context=context)
This is a great trick when "context" is "self".
--
Eric.
More information about the Python-ideas
mailing list