[Python-Dev] converting the stdlib to str.format

Nick Coghlan ncoghlan at gmail.com
Thu Jun 5 14:43:20 CEST 2008


Raymond Hettinger wrote:
> From: "Antoine" <solipsis at pitrou.net
>>  For me the problem is not about ditching the % operator for an
>> intuitively-named method like format(). It's the format syntax which has
>> become much more complicated and error-prone without any clear advantage.
> 
> It's seems that way to me too.  But, it may be one of those things that 
> you quickly get used to.

%r is about the worst case for the new syntax relative to the old - two 
characters become 5. It's worth looking at what those extra characters 
buy us though:

{0!r}

{}: Conversion to a bracketed format is what allows us the flexibility 
to permit arbitrary format strings (such as datetime formatting), as 
well as the

0: Explicit positional argument references allow arguments to be re-used 
(not quite sold on this one personally - surely named arguments are even 
better for that?)

!: Explicit separators (: or !) allow the option of flexible 
object-controlled formatting, while still permitting the basic 
formatting of str/repr/ascii if desired.

I'm really starting to wonder if supporting positional arguments to 
str.format() *at all* is a mistake. Maybe we should ditch support for 
positional arguments and just accept a single dictionary as the sole 
parameter to format().

For dictionary formatting, str.format() is a clear winner over 
str.__mod__(). For positional formatting I'm not so sure - if someone 
decided to convert from %-formatting to str.format, would it be such a 
burden to ask them to name their substitution variables in the process?

Silly example:

"%s occurs %s times in this format string" % (2, 2)

"{0} occurs {0} times in this format string".format(2)

"{num} occurs {num} times in this format string".format(dict(num=2))

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list