[Python-ideas] String formatting and namedtuple

Eric Smith eric at trueblade.com
Sat Feb 14 11:40:39 CET 2009


Guido van Rossum wrote:
> It is true that the advantages of .format() are probably more
> appreciated when you are writing a larger program.

True. I think that the auto-number feature goes a little way in helping 
replace casual uses of %-formatting.

To that end, I've implemented a string.Formatter subclass that mostly 
implements this suggestion, just so people can try it out if they want. 
I believe it's complete, except it doesn't handle escaping '{' and '}'. 
It's attached to http://bugs.python.org/issue5237 as 
auto_number_formatter_3.py.

$ ./python
Python 2.7a0 (trunk:69608, Feb 14 2009, 04:51:18)
[GCC 4.1.2 20070626 (Red Hat 4.1.2-13)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> from auto_number_formatter_3 import formatter as _
 >>> _('{} {} {}').format(3, 'pi', 3.14)
'3 pi 3.14'
 >>>

It also lets you add in format specifiers, conversion specifiers, and 
object access. Once you use those, the improvement of leaving out the 
index numbers is less clear. I'll leave it for debate if this is useful. 
I think it probably is, if only because it's easier to explain the 
behavior: If you leave out the 'field name', a sequential number is 
added in front of the 'replacement string' (using PEP 3101 nomenclature).

 >>> _('{} {} {}').format(3, 'pi', 3.14)
'3 pi 3.14'
 >>> _('{:#b} {!r:^16} {.imag}').format(3, set([14,3]), 3j+1)
'0b11   set([3, 14])   3.0'
 >>>

It also supports all of the regular ''.format() behavior, you just can't 
mix-and-match using field names and omitting them.

 >>> _('{foo:10}').format(foo='bar')
'bar       '
 >>> _('{0} {}').format(1, 2)
Traceback (most recent call last):
  ... <details omitted for clarity>
ValueError: cannot mix and match auto indexing
 >>>

As I said, pure-Python example doesn't handle escaping '{' and '}' 
(because the parsing is tedious and already implemented in the C 
version), but is otherwise complete. If the consensus is that this is 
useful, I'll implement it in ''.format(), otherwise I'm done with this 
issue.

Eric.

PS: Just as a plug, I should note this is the first use I've found for 
the under-appreciated string.Formatter.




More information about the Python-ideas mailing list