[Python-ideas] One way to do format and print

Ron Adam ron3200 at gmail.com
Mon Sep 7 19:32:22 CEST 2015

On 09/07/2015 07:21 AM, Chris Angelico wrote:
>> Where the locals() trick comes in handy is when your template string is
>> >not hard-coded:
>> >
>> >     if greet:
>> >         template = "Hello, I am {name}, and my favourite %s is {%s}."
>> >     else:
>> >         template = "My favourite %s is {%s}."
>> >     if condition:
>> >         template = template % ("number", "x")
>> >     else:
>> >         template = template % ("colour", "c")
>> >     print(template.format_map(locals())

> It's still a poor equivalent for the others. In terms of "why do we
> have so many different ways to do the same thing", the response is
> "the good things to do with format_map(locals()) are not the things
> you can do with f-strings". If what you're looking for can be done
> with either, it's almost certainly not better to use locals().

The ability for a format string or template to take a mapping is very 
useful.  Weather or not it's ok for that mapping to be from locals() is 
a separate issue and depends on other factors as well.  It may be 
perfectly fine in some cases, but not so in others.

The issue with + concatenation is it doesn't call str on the objects. 
That can't be changed.  A new operator (or methods on str) that does 
that could work.  It's still not as concise as f-strings which I think 
is a major motivation for having them.


More information about the Python-ideas mailing list